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);
});
Thanks to johanneslink, the solution is actually simple: