JUnit中Java语法问题:最后一行断言代码执行失败
问题:Assertions.assertThrows未捕获到预期异常导致测试失败
测试代码
CustomErrorDecoder customErrorDecoder = new CustomErrorDecoder(); Response response = Mockito.mock(Response.class); Mockito.when(response.status()).thenReturn(400); Assertions.assertEquals(BadRequestException.class,customErrorDecoder.decode("hdjhsdjs",response).getClass()); Assertions.assertThrows(BadRequestException.class,() -> { customErrorDecoder.decode("hdjhsdjs",response); });
报错信息
Expected uk.co.vw.exception.BadRequestException to be thrown, but nothing was thrown.
org.opentest4j.AssertionFailedError: Expected uk.co.vw.exception.BadRequestException to be thrown, but nothing was thrown.
原因分析
第一句断言能通过,说明decode方法在400状态下返回了一个BadRequestException实例,而非主动抛出该异常。
Assertions.assertThrows的作用是验证代码块执行时会主动抛出指定异常,但如果方法只是把异常对象作为返回值返回,而非通过throw语句抛出,assertThrows自然捕获不到任何异常,导致测试失败。
解决方案
- 检查
CustomErrorDecoder的decode方法实现:- 如果该方法的设计目标是在400状态下抛出BadRequestException,修改方法逻辑,将返回异常对象的代码改为
throw new BadRequestException(...)。 - 如果该方法的设计就是返回异常对象(比如某些自定义ErrorDecoder的约定),则第二句断言不应使用
assertThrows,沿用第一句的方式验证返回值类型即可。
- 如果该方法的设计目标是在400状态下抛出BadRequestException,修改方法逻辑,将返回异常对象的代码改为
内容的提问来源于stack exchange,提问作者Loner shushman
相关产品推荐
相关产品推荐

