Mocking statement when the input parameter of method as exception

时光毁灭记忆、已成空白 提交于 2020-01-16 20:06:12

问题


I'm writing Junit test case for the below scenario and need some suggestions to cover the below snippet:

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

I tried passing ringName as null or empty but not sure how to mock exception block. Can someone please give a suggestion?

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 
    }
}

回答1:


As @AndyTurner pointed out the answer to your question is related on how you declare a method and how code coverage is measured.

Check the Utils class below for 2 version of (basically) the same method.

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;
    }
}

Executing Example1.test(true) with a 'code coverage tool' leads to the line with the handleException method marked as not covered.


static class Example2 {
    public boolean test(boolean flag) throws Exception {
        if (flag) {
            throws Utils.handleException2(new Exception());
        }
        return true;
    }
}

Executing Example2.test(true) with a 'code coverage tool' leads to the line marked as covered.


As @AndyTurner pointed out, the reason for that is that in Example1 the 'compiler' / 'code coverage tool' does not know that the method handleException1 will never return. It expects that such a path exists and therefore does not mark this line as covered.

In Example2 it sees the throws keyword and knows that if this point in the code the method ends here. Therefore all possible pathes are covered.


Whether or not you want (or need) to mock the method is an entirely different question. But judging from your question(s) your aim was to achieve code coverage, so changing your code should solve that issue.



来源:https://stackoverflow.com/questions/57264067/mocking-statement-when-the-input-parameter-of-method-as-exception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!