Home >Java >javaTutorial >How Can JUnit 5\'s `assertThrows()` Simplify Exception Testing?

How Can JUnit 5\'s `assertThrows()` Simplify Exception Testing?

Barbara Streisand
Barbara StreisandOriginal
2024-11-26 15:49:11760browse

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()

  • Permits testing of multiple exceptions within a single test
  • Embraces the power of lambda expressions in Java 8
  • Represents the recommended approach for exception testing in JUnit

Использование assertThrows()

The syntax of assertThrows() is concise and intuitive:

assertThrows(expectedExceptionClass, supplier, message)
  • expectedExceptionClass: Specifies the expected exception type
  • supplier: A lambda expression that invokes the code anticipated to throw an exception
  • message: An optional message to be displayed if the exception is not thrown

Пример использования

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!

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