Mentre stavo testando alcuni casi, ho scoperto che probabilmente non hai coperto il caso, quando viene lanciata un'eccezione non rilevata.
Dato il seguente esempio:
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");
}
}
}
Questo esempio servirà solo a prendere uno dei due rami nel blocco finally perché non si prova il caso, se un'eccezione unchecked (cioè un NullPointerException) sarà gettato.
Quindi, se si cambia TestCase un po ', si prenderà tutte le filiali nel blocco finally:
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 altri miei TestCase ho avuto un caso sligthly diverso con qualche if-else-if
costrutto.
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");
}
}
}
Qui il else if
non prendere il secondo ramo perché, che cosa succede se la condizione if
eelse if
non sarà vero? Verrà rilevato anche se fornisci altri valori rispetto a entrambi nella dichiarazione if-else-if
.
"Da notare anche la cattura speciale aggiunto apparirà nel bytecode anche se scrivi esplicitamente catch (Lancio a mano). " - Credo che questo sia sbagliato, cioè 'catch (java/lang/Throwable)' e 'catch (any)' - due distinti gestori di eccezioni in bytecode, anche se 'Throwable' è una classe base di tutti gli errori e le eccezioni. –
Godin