首页 > 解决方案 > 方法的输入参数为异常时的模拟语句

问题描述

我正在为以下场景编写 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 
    }
}

标签: javajunitmockito

解决方案


正如所@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关键字并知道如果代码中的这一点,方法就在这里结束。因此涵盖了所有可能的路径。


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


推荐阅读