Junit5: Expect nested exception

1.7k Views Asked by At

How does JUnit 5 allow to check for a nested exception? I'm looking for something similar to what could be done in JUnit 4 with the help of a @org.junit.Rule, as shown in the following snippet:

class MyTest {

    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    @Test
    public void checkForNestedException() {

        // a JPA exception will be thrown, with a nested LazyInitializationException
        expectedException.expectCause(isA(LazyInitializationException.class));

        Sample s = sampleRepository.findOne(id);

        // not touching results triggers exception
        sampleRepository.delete(s);
    }
}

Edit as per comment:

Assertions.assertThrows(LazyInitializationException.class) does not work in JUnit 5, since LazyInitializationException is the nested exception (cause) of JpaSystemException.

Only the check for the outer exception can be made, which does not work as desired:

// assertThrows does not allow checking for nested LazyInitializationException
Assertions.assertThrows(JpaSystemException.class, () -> {

    Sample s = sampleRepository.getOne(id);

    // not touching results triggers exception
    sampleRepository.delete(s);
});
1

There are 1 best solutions below

0
On

Thanks to johanneslink, the solution is actually simple:

// assertThrows returns the thrown exception (a JpaSystemException)
Exception e = Assertions.assertThrows(JpaSystemException.class, () -> {

    Sample s = sampleRepository.getOne(id);

    // not touching results triggers exception
    sampleRepository.delete(s);
});

// Now the cause of the thrown exception can be checked
assertTrue(e.getCause() instanceof LazyInitializationException);