Home >Java >javaTutorial >How to Effectively Assert Exceptions in JUnit Tests?
Executing Exception Assertions in JUnit Tests
Asserting that a specific exception is thrown during code execution is a common test scenario in JUnit. To do this effectively, JUnit provides several methods that enhance readability and simplify the testing process.
JUnit 5 and 4.13 Assertions
In JUnit 5 and 4.13, the @Test annotation with the expected attribute can be used directly:
@Test public void testIndexOutOfBoundsException() { ArrayList<Object> emptyList = new ArrayList<>(); assertThrows(IndexOutOfBoundsException.class, () -> emptyList.get(0)); }
AssertJ and Google Truth Assertions
External assertion libraries like AssertJ and Google Truth offer additional methods for exception assertions:
AssertJ:
import static org.assertj.core.api.Assertions.*; @Test public void testIndexOutOfBoundsException() { ArrayList<Object> emptyList = new ArrayList<>(); assertThatThrownBy(() -> emptyList.get(0)) .isInstanceOf(IndexOutOfBoundsException.class); }
Google Truth:
import static com.google.common.truth.Truth.*; @Test public void testIndexOutOfBoundsException() { ArrayList<Object> emptyList = new ArrayList<>(); assertThatCode(() -> emptyList.get(0)).willThrow(IndexOutOfBoundsException.class); }
JUnit Pre-4.13 Assertions (Deprecated)
For JUnit versions prior to 4.13, a more cumbersome approach was to manually check for the exception within a try-catch block:
@Test public void testIndexOutOfBoundsException() { boolean thrown = false; ArrayList<Object> emptyList = new ArrayList<>(); try { emptyList.get(0); // Intentionally triggers an exception } catch (IndexOutOfBoundsException e) { thrown = true; } assertTrue(thrown); }
This approach is deprecated and less idiomatic than the aforementioned methods. Refer to the [JUnit Test-FAQ](https://junit.org/junit4/faq.html) for more details.
The above is the detailed content of How to Effectively Assert Exceptions in JUnit Tests?. For more information, please follow other related articles on the PHP Chinese website!