HiveBrain v1.2.0
Get Started
← Back to all entries
debugjavaCritical

How to assert an exception is thrown with JUnit 5?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
withhowthrownjunitexceptionassert

Problem

Is there a better way to assert that a method throws an exception in JUnit 5?

Currently, I have to use a @Rule in order to verify that my test throws an exception, but this doesn't work for the cases where I expect multiple methods to throw exceptions in my test.

Solution

You can use assertThrows(), which allows you to test multiple exceptions within the same test. With support for lambdas in Java 8, this is the canonical way to test for exceptions in JUnit.

Per the JUnit docs:
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"));
}

Context

Stack Overflow Q#40268446, score: 1035

Revisions (0)

No revisions yet.