Home >Java >javaTutorial >How to Assert Exceptions in JUnit Tests: JUnit 4, JUnit 5, AssertJ, and Google Truth?

How to Assert Exceptions in JUnit Tests: JUnit 4, JUnit 5, AssertJ, and Google Truth?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-25 08:54:10545browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn