In JUnit, testing whether a specific exception is thrown can be achieved in multiple ways.
The @Test annotation now supports the expected attribute, which allows you to specify the expected exception type:
@Test(expected = IndexOutOfBoundsException.class) public void testIndexOutOfBoundsException() { ArrayList emptyList = new ArrayList(); Object o = emptyList.get(0); }
Third-party assertion libraries like AssertJ and Google Truth provide more concise syntax for exception testing:
// AssertJ assertThatThrownBy(() -> foo.doStuff()).isInstanceOf(IndexOutOfBoundsException.class); // Google Truth assertWithMessage("Expected IndexOutOfBoundsException").thatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> foo.doStuff());
For JUnit 4.12 and earlier, there are several options:
Refer to the JUnit Test-FAQ for more details on these options.
The above is the detailed content of How Can I Effectively Test for Exception Handling in JUnit?. For more information, please follow other related articles on the PHP Chinese website!