Home >Java >javaTutorial >How Does JUnit 5\'s `assertThrows()` Simplify Exception Testing?
In JUnit 5, asserting that a method throws an exception has become more flexible and efficient with the introduction of the assertThrows() method. This method eliminates the need for the cumbersome @Rule approach, especially when dealing with multiple expected exceptions within a single test.
The assertThrows() method accepts multiple arguments:
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")); }
In this example, the test expects the doThing() method to throw a MyException with a message containing "Stuff." If the exception is not thrown or if the message does not match, the test will fail.
Compared to @Rule, assertThrows() offers several advantages:
JUnit 5's assertThrows() method empowers developers with a concise and efficient way to assert exception throwing in their tests. By streamlining the process and providing improved error messages, assertThrows() makes exception testing more reliable and maintainable.
The above is the detailed content of How Does JUnit 5's `assertThrows()` Simplify Exception Testing?. For more information, please follow other related articles on the PHP Chinese website!