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