java - 方法的输入参数为异常时的模拟语句
问题描述
我正在为以下场景编写 Junit 测试用例,需要一些建议来涵盖以下代码段:
ErrorHandlingUtils.manageException(new InvalidInputException("Ethernet Ring Name not found"),methodName);
我尝试ringName
以 null 或空的形式传递,但不确定如何模拟异常块。有人可以给个建议吗?
public void deleteEthernetRing(String ringName, String userID) throws Exception {
LOGGER.info("Delete Ethernet Ring ");
String methodName = "Delete Ethernet Ring ";
ResponsePayLoad returnVal = new ResponsePayLoad();
HttpHeaders responseHeaders = new HttpHeaders();
if (StringUtils.isBlank(ringName))
// NOT COVERED
ErrorHandlingUtils.manageException(new InvalidInputException("Ethernet Ring Name not found"),methodName);
if (userID == null || userID.isEmpty()) {
ErrorHandlingUtils.manageException(new InvalidInputException("UserID Must be provided to remove Ring"),methodName);
} else {
// The actual business logic
}
}
解决方案
正如所@AndyTurner
指出的,您的问题的答案与您如何声明方法以及如何测量代码覆盖率有关。
检查下面的 Utils 类以获取(基本上)相同方法的 2 个版本。
static class Utils {
public static void handleException1(Exception e) throws Exception {
throw e;
}
public static Exception handleException2(Exception e) {
return e;
}
}
static class Example1 {
public boolean test(boolean flag) throws Exception {
if (flag) {
Utils.handleException1(new Exception());
}
return true;
}
}
使用“代码覆盖工具”执行Example1.test(true)
会导致handleException
方法标记为未覆盖。
static class Example2 {
public boolean test(boolean flag) throws Exception {
if (flag) {
throws Utils.handleException2(new Exception());
}
return true;
}
}
使用“代码覆盖工具”执行Example2.test(true)
会导致标记为已覆盖的行。
正如所@AndyTurner
指出的,这样做的原因是在Example1
“编译器”/“代码覆盖工具”中不知道该方法handleException1
永远不会返回。它期望存在这样的路径,因此不会将此行标记为已覆盖。
在Example2
它看到throws
关键字并知道如果代码中的这一点,方法就在这里结束。因此涵盖了所有可能的路径。
您是否想要(或需要)模拟该方法是一个完全不同的问题。但是从您的问题来看,您的目标是实现代码覆盖率,因此更改代码应该可以解决该问题。
推荐阅读
- javascript - Webpack如何否定匹配资源查询
- image - React Native Image错误道具类型失败:提供给ForwardRef(Image)的道具源无效
- swift - ios swift 编程与 view..visible 和 view.gone
- python - R 的 Dexp 函数在 Python 中等效
- templates - 文本模板不适用于某些单词
- android - 针对 SDK Android Q 导致无法完成会话:INSTALL_FAILED_INVALID_APK: 无法提取本机库,res=-2
- jenkins - Jenkins Blue Ocean 在 GitHub 'git checkout -b branch-name' 上失败,状态码为 128:
- javascript - 在我的应用程序的登录页面上显示 git 标签(版本)
- visual-studio-code - 如何在 VS Code 调试器中更改默认启动设置
- angular - 身份服务器检索用户详细信息