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
Release: 2024-12-25 08:54:10
Original
541 people have browsed it

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template