Exception Testing with JUnit

Testing exceptions can be done with the @Test annotation and its expected property. The message of the exception has to be asserted in a catch-block. This test seems a bit cumbersome.


@Test(expected = IllegalArgumentException.class)
public void exceptionTesting() {
try {
throw new IllegalArgumentException("id must not be null");
}
catch(IllegalArgumentException iae) {
assertEquals("id must not be null", iae.getMessage());
throw iae;
}
}

Since JUnit 4.7, it is possible to use the @Rule annotation to expect exceptions. In this way, the test can be expressed quite more elegantly.


@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void shouldThrowExpectedException(){
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("id must not be null");
throw new IllegalArgumentException("id must not be null");
}

In JUnit 5, we use Java 8 Lambdas to describe the same test.


@Test
void exceptionTesting() {
Throwable exception = expectThrows(IllegalArgumentException.class, () -> {
throw new IllegalArgumentException("id must not be null");
});
assertEquals("id must not be null", exception.getMessage());
}

Werbung