How do you assert that a certain exception is thrown in JUnit 4 tests? How do you assert that a certain exception is thrown in JUnit 4 tests? java java

How do you assert that a certain exception is thrown in JUnit 4 tests?


It depends on the JUnit version and what assert libraries you use.

The original answer for JUnit <= 4.12 was:

@Test(expected = IndexOutOfBoundsException.class)public void testIndexOutOfBoundsException() {    ArrayList emptyList = new ArrayList();    Object o = emptyList.get(0);}

Though answer https://stackoverflow.com/a/31826781/2986984 has more options for JUnit <= 4.12.

Reference :


Edit: 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 my other answer for details.

If you haven't migrated to JUnit 5, but can use JUnit 4.7, you can use the ExpectedException Rule:

public class FooTest {  @Rule  public final ExpectedException exception = ExpectedException.none();  @Test  public void doStuffThrowsIndexOutOfBoundsException() {    Foo foo = new Foo();    exception.expect(IndexOutOfBoundsException.class);    foo.doStuff();  }}

This is much better than @Test(expected=IndexOutOfBoundsException.class) because the test will fail if IndexOutOfBoundsException is thrown before foo.doStuff()

See this article for details.


Be careful using expected exception, because it only asserts that the method threw that exception, not a particular line of code in the test.

I tend to use this for testing parameter validation, because such methods are usually very simple, but more complex tests might better be served with:

try {    methodThatShouldThrow();    fail( "My method didn't throw when I expected it to" );} catch (MyException expectedException) {}

Apply judgement.