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