In JUnit, testing code that should throw an exception requires a clean and concise approach. While manually checking for exceptions is possible, it's not the idiomatic way.
In JUnit versions 5 and 4.13, you can use @Test(expected = ExceptionClass.class) annotation on the test method. This expects the specified exception to be thrown.
Example:
@Test(expected = IndexOutOfBoundsException.class) public void testIndexOutOfBoundsException() { ArrayList emptyList = new ArrayList(); emptyList.get(0); }
If using libraries like AssertJ or Google-Truth, you can employ their assertions for validating exceptions.
AssertJ:
import static org.assertj.core.api.Assertions.assertThatThrownBy; @Test public void testFooThrowsIndexOutOfBoundsException() { assertThatThrownBy(() -> foo.doStuff()).isInstanceOf(IndexOutOfBoundsException.class); }
Google-Truth:
import static com.google.common.truth.Truth.assertThat; @Test public void testFooThrowsIndexOutOfBoundsException() { assertThat(assertThrows(IndexOutOfBoundsException.class, foo::doStuff)).isNotNull(); }
In JUnit versions less than or equal to 4.12, you can use Rule or TryCatch to handle exceptions.
Using Rule:
@Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testIndexOutOfBoundsException() { thrown.expect(IndexOutOfBoundsException.class); ArrayList emptyList = new ArrayList(); emptyList.get(0); }
Using TryCatch:
import static org.junit.Assert.assertEquals; @Test public void testIndexOutOfBoundsException() { try { ArrayList emptyList = new ArrayList(); emptyList.get(0); fail("IndexOutOfBoundsException was expected"); } catch (IndexOutOfBoundsException e) { assertEquals(e.getClass(), IndexOutOfBoundsException.class); } }
The above is the detailed content of How Do I Assert Exception Handling in JUnit Tests?. For more information, please follow other related articles on the PHP Chinese website!