Home >Java >javaTutorial >How to Assert Exceptions in JUnit Tests: JUnit 4, JUnit 5, AssertJ, and Google Truth?
How to Assert Exception in JUnit Tests
Testing for exceptions in JUnit should be done idiomatically. Avoid using verbose code like manually catching and asserting the exception.
JUnit 5 and 4.13:
Add the @Test(expected = MyException.class) annotation to your test method, where MyException is the expected exception.
AssertJ and google-truth:
Use the assertThatExceptionOfType(MyException.class) method to assert that an exception of type MyException is thrown.
Legacy JUnit (<= 4.12):
While considered less idiomatic, you can still use the @Test(expected = MyException.class) annotation or the Rule interface to assert exceptions. Additionally, use assertThrows(MyException.class, () -> { ... }) with JUnit 5.
The above is the detailed content of How to Assert Exceptions in JUnit Tests: JUnit 4, JUnit 5, AssertJ, and Google Truth?. For more information, please follow other related articles on the PHP Chinese website!