Is there a JUnit5 equivalent of ExpectedException.expectCause()
(JUnit4)?
https://junit.org/junit4/javadoc/4.12/org/junit/rules/ExpectedException.html#expectCause(org.hamcrest.Matcher)
You can use assertThrows() , But with assertThrows your assertion will pass even if the thrown exception is of child type. This is because, JUnit 5 checks exception type by calling Class. isIntance(..) , Class. isInstance(..) will return true even if the thrown exception is of a child type.
Usage. You have to add the ExpectedException rule to your test. This doesn't affect your existing tests (see throwsNothing() ). After specifiying the type of the expected exception your test is successful when such an exception is thrown and it fails if a different or no exception is thrown.
When using JUnit 4, we can simply use the expected attribute of the @Test annotation to declare that we expect an exception to be thrown anywhere in the annotated test method. In this example, we've declared that we're expecting our test code to result in a NullPointerException.
Here is an example:
public class ExpectedExceptionTest {
@Test
public void shouldThrow() {
IOException exc = Assertions.assertThrows(IOException.class, this::throwing);
Assertions.assertEquals("root cause", exc.getCause().getMessage());
}
private void throwing() throws IOException {
throw new IOException(new IllegalStateException("root cause"));
}
}
Personally, I prefer AssertJ which has very descriptive exception assertions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With