Home >Java >javaTutorial >How Can JUnit 5\'s `assertThrows()` Simplify Exception Testing?
Enhanced Exception Assertions in JUnit 5
While @Rule was previously employed to verify exception handling in JUnit 5, it posed limitations when testing multiple exceptions within a single test. To streamline this process and gain additional flexibility, JUnit 5 introduced assertThrows().
преимущества использования assertThrows()
Использование assertThrows()
The syntax of assertThrows() is concise and intuitive:
assertThrows(expectedExceptionClass, supplier, message)
Пример использования
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")); }
By leveraging assertThrows(), you can now efficiently test for exceptions in JUnit 5, ensuring robust and thorough testing of your code.
The above is the detailed content of How Can JUnit 5\'s `assertThrows()` Simplify Exception Testing?. For more information, please follow other related articles on the PHP Chinese website!