Junit5:预期嵌套异常

Mar*_*idt 2 nested-exceptions junit5

JUnit 5 如何允许检查嵌套异常?我正在寻找类似于在 JUnit 4 中借助 a 可以完成的操作@org.junit.Rule,如以下代码片段所示:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

根据评论编辑:

Assertions.assertThrows(LazyInitializationException.class)在 JUnit 5 中不起作用,因为LazyInitializationException是 的嵌套异常(原因)JpaSystemException

只能检查外部异常,这不能按预期工作:

// 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);
});
Run Code Online (Sandbox Code Playgroud)

Mar*_*idt 5

感谢 johanneslink,解决方案实际上很简单:

// 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);
Run Code Online (Sandbox Code Playgroud)