You need to enable JavaScript to run this app. 如何在Java单元测试中构造响应头返回值完成断言?
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java单元测试中构造响应头返回值完成断言?

问题根源

你的测试代码仅Mock了响应的状态码为200,缺失了响应头相关方法的Mock定义:业务代码需要从HttpResponse的头信息中取出LOCATION对应的第一个值,但你没有指定当调用httpResponse.headers()、以及头对象调用allValues(LOCATION)时的返回值,Mockito会默认返回空列表/空对象,要么触发索引越界进入异常捕获分支,要么取到空值,最终返回null。

解决步骤

  1. 新增HttpResponse.Headers类型的Mock对象
  2. 补充响应头相关方法的Mock规则,指定LOCATION对应的返回值列表

修改后的测试代码示例

@ExtendWith(MockitoExtension.class)
class ClassToTest {

    private final static String URL = "https://myUrl/";
    private final static String ACCESS_TOKEN = "access_token";
    // 定义预期返回的LOCATION值
    private final static String EXPECTED_LOCATION = "UUID";

    private final Clock clock = Clock.fixed(Instant.now(), ZoneId.of("UTC"));

    private ClassToTest service;

    @Mock
    private HttpClient httpClient;

    @Mock
    private OAuth oAuthClient;

    @Mock
    private HttpResponse httpResponse;
    // 新增响应头Mock
    @Mock
    private HttpResponse.Headers responseHeaders;

    @BeforeEach
    void setUp() {
        service = new ClassToTest(httpClient, oAuthClient);
        when(config.getValue(SERVICE_URL)).thenReturn(AVISO_URL);
        when(oAuthClient.getToken()()).thenReturn(ACCESS_TOKEN);
    }

    @Test
    void myMethod_toTest_success() throws IOException, InterruptedException {
        when(httpClient.send(any(HttpRequest.class), any(HttpResponse.BodyHandler.class))).thenReturn(httpResponse);
        when(httpResponse.statusCode()).thenReturn(HttpStatus.OK.value());
        // 补充响应头相关Mock规则
        when(httpResponse.headers()).thenReturn(responseHeaders);
        // 注意LOCATION要和业务代码中使用的常量完全一致
        when(responseHeaders.allValues(LOCATION)).thenReturn(List.of(EXPECTED_LOCATION));

        var result = service.myMethod(myItem);
        assertEquals(EXPECTED_LOCATION, result);
    }
...
}

注意事项

  • 确保Mock时使用的LOCATION常量和业务代码中定义的常量值完全一致,大小写、拼写都不能出错
  • 如果业务代码中HttpBodyHandlers.ofCodec()有自定义逻辑,可将any(HttpResponse.BodyHandler.class)替换为精确匹配规则,避免参数匹配失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 13:36:05