Asserting Exceptions in JUnit 5 with Assertions.assertThrows()
In JUnit 5, asserting that a method throws an exception can be achieved through the Assertions.assertThrows() method. This provides a convenient and expressive way to test various exception scenarios, particularly when dealing with multiple exceptions in a single test.
Consider the following test case:
import static org.junit.jupiter.api.Assertions.assertThrows; @Test void exceptionTesting() { MyException thrown = assertThrows( MyException.class, () -> myObject.doThing(), "Expected doThing() to throw, but it didn't" ); assertTrue(thrown.getMessage().contains("Stuff")); }
Here's how Assertions.assertThrows() works:
Benefits of Using Assertions.assertThrows():
The above is the detailed content of How to Assert Exceptions in JUnit 5 using Assertions.assertThrows()?. For more information, please follow other related articles on the PHP Chinese website!