1

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);
    }
}

根据评论编辑:

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);
});
4

1 回答 1

2

感谢 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);
于 2021-01-14T09:11:45.507 回答