Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit5 - ExpectedException.expectCause() equivalent

Tags:

junit5

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)

like image 784
Florian Lopes Avatar asked Nov 22 '18 13:11

Florian Lopes


People also ask

How do you catch exceptions in JUnit 5?

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.

How do you use ExpectedException?

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.

How do you check if an exception is thrown JUnit?

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.


1 Answers

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.

like image 98
Harald Wellmann Avatar answered Nov 11 '22 06:11

Harald Wellmann