gpt4 book ai didi

Junit5:预期嵌套异常

转载 作者:行者123 更新时间:2023-12-03 08:29:03 28 4
gpt4 key购买 nike

JUnit 5 如何允许检查嵌套异常?我正在寻找类似于 JUnit 4 借助 @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 中不起作用,因为 LazyInitializationExceptionJpaSystemException 的嵌套异常(原因) .

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

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

最佳答案

感谢 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);

关于Junit5:预期嵌套异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65686127/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com