gpt4 book ai didi

java - 方法的输入参数为异常时的Mock语句

转载 作者:行者123 更新时间:2023-12-02 02:24:11 24 4
gpt4 key购买 nike

我正在为以下场景编写 Junit 测试用例,需要一些建议来涵盖以下代码片段:

ErrorHandlingUtils.manageException(new InvalidInputException("Ethernet Ring Name not found"),methodName);

我尝试将 ringName 作为 null 或空传递,但不确定如何模拟异常 block 。有人可以给个建议吗?

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关键字并知道如果代码中的这一点该方法在此结束。因此,所有可能的路径都被覆盖。

<小时/>

您是否想要(或需要)模拟该方法是一个完全不同的问题。但从您的问题来看,您的目标是实现代码覆盖率,因此更改代码应该可以解决该问题。

关于java - 方法的输入参数为异常时的Mock语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57264067/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com