While I was testing some cases, I found out, that you probably don't have covered the case, when a not catched Exception is thrown.
Given the following example:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.junit.Test;
public class CodeCoverageFinallyTest {
@Test
public void testMyMethod() {
myMethod("2015-08-31");
myMethod("wrongFormat");
}
private void myMethod(final String source) {
try {
new SimpleDateFormat("yyyy-MM-dd").parse(source);
} catch (final ParseException e) {
System.out.println("catch ParseException");
} finally {
System.out.println("finally");
}
}
}
This example will only catch one of the two branches in the finally block because you don't test the case, if a unchecked exception (i.e. a NullPointerException) will be thrown.
So, if you change your testcase a bit, you will catch all branches in the finally block:
public void testMyMethod() {
myMethod("2015-08-31");
myMethod("wrongFormat");
myMethod(null); // also cover the case, that an unchecked and unhandled exception
// will be thrown
}
In my other testcase I had a sligthly different case with some if-else-if
construct.
import org.junit.Test;
public class CodeCoverageIfElseTest {
@Test
public void testMyMethod() {
myMethod("2015-08-31");
myMethod("wrongFormat");
}
private void myMethod(final String source) {
if ("2015-08-31".equals(source)) {
System.out.println("Correct format");
} else if ("wrongFormat".equals(source)) {
System.out.println("Incorrect format");
}
}
}
Here the else if
didn't catch the second branch because, what if the if
and else if
condition won't be true? It will also be caught, if you provide other values than the both in the if-else-if
statement.
catch(java/lang/Throwable)
andcatch(any)
- two distinct exception handlers in bytecode, even ifThrowable
is a base class of all errors and exceptions. – Prothonotary