Dipende da cosa si desidera controllare nell'eccezione. Se tutto quello che stai facendo è verificare che l'eccezione viene generata, quindi utilizzando @Test(expected=...)
è probabilmente il modo più semplice:
@Test(expected=CustomException.class)
public void checkNullObject() throws CustomException {
MyClass myClass= null;
MyCustomClass.get(null);
}
Tuttavia, il @Rule ExpectedException ha molte più opzioni, tra cui il controllo del messaggio, dal javadoc :
// These tests all pass.
public static class HasExpectedException {
@Rule
public ExpectedException thrown= ExpectedException.none();
@Test
public void throwsNothing() {
// no exception expected, none thrown: passes.
}
@Test
public void throwsNullPointerException() {
thrown.expect(NullPointerException.class);
throw new NullPointerException();
}
@Test
public void throwsNullPointerExceptionWithMessage() {
thrown.expect(NullPointerException.class);
thrown.expectMessage("happened?");
thrown.expectMessage(startsWith("What"));
throw new NullPointerException("What happened?");
}
@Test
public void throwsIllegalArgumentExceptionWithMessageAndCause() {
NullPointerException expectedCause = new NullPointerException();
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("What");
thrown.expectCause(is(expectedCause));
throw new IllegalArgumentException("What happened?", cause);
}
}
Quindi è possibile verificare il messaggio, la causa originale dell'eccezione. Per controllare il messaggio, è possibile utilizzare i corrispondenti, in modo da poter controllare startsWith()
e simili.
Un motivo per utilizzare il vecchio stile (Junit 3) tiro/presa è se si hanno requisiti specifici. Non ci sono molti di questi, ma può succedere:
@Test
public void testMe() {
try {
Integer.parseInt("foobar");
fail("expected Exception here");
} catch (Exception e) {
// OK
}
}
fonte
2012-07-11 09:25:27
Io uso il secondo modulo. –
Usiamo anche il secondo modulo. – SWoeste
O un duplicato di http://stackoverflow.com/questions/785618/in-java-how-can-i-validate-a-thrown-exception-with-junit o principalmente opinion based – Raedwald