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

Spring MVC集成测试:仅在响应状态非OK时打印响应内容

解决MockMvc仅在响应非OK时打印响应内容的问题

在Spring集成测试中,默认的print()方法会输出完整的请求和响应信息,容易导致日志冗余。要实现仅在响应状态非OK时打印响应内容(不含请求),可以通过自定义ResultHandler来实现:

实现方式1:内联Lambda表达式

直接在测试代码中用Lambda定义逻辑,无需额外方法:

mockMvc.perform(post("/xyz")
                .contentType(MediaType.APPLICATION_JSON)
                .content("{\"key\":\"value\"}"))
        .andDo(result -> {
            int statusCode = result.getResponse().getStatus();
            if (statusCode != HttpStatus.OK.value()) {
                System.out.println("=== 错误响应信息 ===");
                System.out.println("状态码: " + statusCode);
                System.out.println("响应体: " + result.getResponse().getContentAsString(StandardCharsets.UTF_8));
            }
        })
        .andExpect(status().isOk());

实现方式2:提取为复用工具方法

如果多个测试用例需要用到该逻辑,可以将其提取为测试类中的工具方法:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.ResultHandler;
import java.nio.charset.StandardCharsets;

private static final Logger log = LoggerFactory.getLogger(YourTestClass.class);

private ResultHandler printErrorResponse() {
    return result -> {
        MockHttpServletResponse response = result.getResponse();
        int statusCode = response.getStatus();
        if (statusCode != HttpStatus.OK.value()) {
            log.warn("=== 请求失败 ===");
            log.warn("状态码: {}", statusCode);
            log.warn("响应体: {}", response.getContentAsString(StandardCharsets.UTF_8));
        }
    };
}

// 使用示例
mockMvc.perform(post("/xyz")
                .contentType(MediaType.APPLICATION_JSON)
                .content("{\"key\":\"value\"}"))
        .andDo(printErrorResponse())
        .andExpect(status().isOk());

关键说明

  • 自定义ResultHandler会在请求执行后立即检查响应状态,仅在非OK时打印内容,避免正常请求的日志干扰。
  • 推荐用日志框架(如SLF4J)代替System.out,便于统一管理日志级别和格式。
  • 注意执行顺序:andDo()要放在andExpect()之前,确保即使断言失败,错误响应也能被正常打印。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 00:58:19