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

MockHttpServletResponse测试时ContentCachingResponseWrapper.getContentAsByteArray()为空

问题根因

  • ContentCachingResponseWrapper是装饰器模式实现,仅会捕获包装完成后,通过该wrapper实例写入的响应内容。你在测试中提前将响应体写入了原始MockHttpServletResponse,这部分内容不会被wrapper感知到。
  • 测试中传入的FilterChain是空Mock实现,filterChain.doFilter()没有执行任何写入响应的逻辑,没有数据写入到wrappedResponse的缓存区,因此getContentAsByteArray()返回空数组。

解决方案

1. 修正单元测试逻辑

将响应写入操作放到FilterChain的模拟实现中,保证写入动作发生在wrapper包装之后、且作用在wrapper实例上:

void myTest() throws ServletException, IOException {
    final String body = "This is a body that my service might return.";
    var testResp = new MockHttpServletResponse();
    // 模拟真实请求链路的响应写入逻辑
    FilterChain mockFilterChain = (request, response) -> {
        response.getWriter().print(body);
        response.getWriter().flush();
        response.setContentLength(body.length());
    };

    myFilter.doFilterInternal(Mockito.mock(HttpServletRequest.class), testResp, mockFilterChain);
    
    // 可选断言验证结果
    assertEquals(body, testResp.getContentAsString());
}

2. 业务逻辑说明

你原本的过滤器代码在生产环境可以正常运行,不需要修改:真实运行时Spring MVC的请求处理、响应写入逻辑都在filterChain.doFilter()执行过程中触发,写入动作会被wrapper捕获。

内容的提问来源于stack exchange,提问作者Joakim M. H.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 15:45:05