如何在JUnit5中校验嵌套异常?对标JUnit4 ExpectedException用法
JUnit5 嵌套异常校验实现方案
很多测试场景中抛出的最外层异常是框架封装的包装异常(比如Spring抛出的JpaSystemException),需要校验的业务实际异常(比如LazyInitializationException)是嵌在异常链路里的cause,而JUnit5原生的Assertions.assertThrows仅能匹配直接抛出的最外层异常类型,无法直接校验深层嵌套的异常原因,以下是完全覆盖JUnit4中ExpectedException.expectCause能力的可落地方案:
零依赖原生实现
注意:原生
Assertions.assertThrows在匹配到最外层异常后,会返回完整的异常实例对象,这是实现嵌套校验的基础。
不需要引入任何第三方依赖,拿到异常实例后顺着getCause()链路遍历匹配即可:
// 捕获最外层抛出的JpaSystemException JpaSystemException outerEx = Assertions.assertThrows( JpaSystemException.class, () -> { Sample s = sampleRepository.getOne(id); sampleRepository.delete(s); } ); // 遍历异常链匹配需要校验的嵌套异常 Throwable currentCause = outerEx.getCause(); boolean isMatched = false; while (currentCause != null) { if (currentCause instanceof LazyInitializationException) { isMatched = true; break; } currentCause = currentCause.getCause(); } Assertions.assertTrue(isMatched, "异常链路中未找到预期的LazyInitializationException");
日常测试中可以把这段遍历逻辑抽成通用工具方法,避免重复编写样板代码。
简洁断言实现(搭配AssertJ)
Spring Boot测试场景默认引入AssertJ依赖,其原生提供的异常断言能力可以完全对齐JUnit4的校验体验,不需要手动写循环遍历逻辑:
Assertions.assertThatExceptionOfType(JpaSystemException.class) .isThrownBy(() -> { Sample s = sampleRepository.getOne(id); sampleRepository.delete(s); }) // 直接校验嵌套cause类型,完全对应JUnit4的expectCause能力 .cause().isInstanceOf(LazyInitializationException.class);
如果不需要卡最外层异常类型,仅需校验异常链路的根因,可直接用rootCause方法匹配:
Assertions.assertThat() .isThrownBy(() -> { Sample s = sampleRepository.getOne(id); sampleRepository.delete(s); }) .rootCause() .isInstanceOf(LazyInitializationException.class);
存量用例兼容迁移方案
如果是从JUnit4迁移存量测试用例,不想改动原有测试逻辑,可引入junit-vintage-engine桥接依赖,原封不动保留原有的@Rule+ExpectedException的写法即可在JUnit5环境下运行,不需要重写异常校验逻辑。
内容的提问来源于stack exchange,提问作者Markus Pscheidt
相关产品推荐
相关产品推荐

