How can I use JUnit4 idiomatically to test that some code throws an exception?
While I can certainly do something like this:
@Test
public void testFo
Now that JUnit 5 and JUnit 4.13 have been released, the best option would be to use Assertions.assertThrows()
(for JUnit 5) and Assert.assertThrows()
(for JUnit 4.13). See
the Junit 5 User Guide.
Here is an example that verifies an exception is thrown, and uses Truth to make assertions on the exception message:
public class FooTest {
@Test
public void doStuffThrowsIndexOutOfBoundsException() {
Foo foo = new Foo();
IndexOutOfBoundsException e = assertThrows(
IndexOutOfBoundsException.class, foo::doStuff);
assertThat(e).hasMessageThat().contains("woops!");
}
}
The advantages over the approaches in the other answers are:
throws
clauseA similar method will be added to org.junit Assert
in JUnit 4.13.