Home > Java > javaTutorial > body text

How to Assert Exceptions in JUnit 5 using Assertions.assertThrows()?

DDD
Release: 2024-11-19 19:04:02
Original
757 people have browsed it

How to Assert Exceptions in JUnit 5 using Assertions.assertThrows()?

Asserting Exceptions in JUnit 5 with Assertions.assertThrows()

In JUnit 5, asserting that a method throws an exception can be achieved through the Assertions.assertThrows() method. This provides a convenient and expressive way to test various exception scenarios, particularly when dealing with multiple exceptions in a single test.

Consider the following test case:

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"));
}
Copy after login

Here's how Assertions.assertThrows() works:

  1. Exception Type: The first argument to assertThrows() is the expected exception type. In this case, we expect MyException to be thrown.
  2. Executable Lambda: The second argument is a lambda expression representing the executable code under test. It should invoke the method that is expected to throw an exception.
  3. Message (Optional): The third argument (optional) allows you to specify a custom error message in case the assertion fails.

Benefits of Using Assertions.assertThrows():

  • Concise and Readable: Assertions.assertThrows() simplifies exception testing compared to using a @Rule, making your tests more compact and readable.
  • Multiple Exceptions Testing: This method allows you to test multiple exceptions within the same test case.
  • Cleaner Assertions: Instead of manually checking for the thrown exception, assertThrows() provides a more concise and declarative way to assert exception conditions.

The above is the detailed content of How to Assert Exceptions in JUnit 5 using Assertions.assertThrows()?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template