You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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自然捕获不到任何异常,导致测试失败。

解决方案

  1. 检查CustomErrorDecoder的decode方法实现:
    • 如果该方法的设计目标是在400状态下抛出BadRequestException,修改方法逻辑,将返回异常对象的代码改为throw new BadRequestException(...)。
    • 如果该方法的设计就是返回异常对象(比如某些自定义ErrorDecoder的约定),则第二句断言不应使用assertThrows,沿用第一句的方式验证返回值类型即可。

内容的提问来源于stack exchange,提问作者Loner shushman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 01:36:25