如何为Spring REST Docs的MockMvc响应体启用JSON格式化?
你遇到的问题很常见——默认情况下,MockMvc输出的响应体和Spring REST Docs生成的文档示例都是单行JSON,可读性很差。下面分两部分解决这个问题:
一、让MockMvc测试日志输出格式化的JSON
你当前用的andDo(print())是MockMvc的默认处理器,它只会输出原始的单行JSON。如果你想在测试日志里看到格式化后的结构,可以用以下两种方法:
方法1:自定义打印处理器
在你的测试类中添加一个工具方法,手动格式化响应体:
private ResultHandler prettyPrintResponse() { return result -> { MockHttpServletResponse response = result.getResponse(); // 用Jackson解析并格式化JSON ObjectMapper objectMapper = new ObjectMapper() .enable(SerializationFeature.INDENT_OUTPUT); String prettyJson = objectMapper.writeValueAsString( objectMapper.readValue(response.getContentAsString(), Object.class) ); // 模拟默认print的输出格式,替换Body为格式化后的内容 System.out.println("MockHttpServletResponse:"); System.out.println(" Status = " + response.getStatus()); System.out.println(" Error message = " + response.getErrorMessage()); System.out.println(" Headers = " + response.getHeaderNames()); System.out.println(" Content type = " + response.getContentType()); System.out.println(" Body = " + prettyJson); System.out.println(" Forwarded URL = " + response.getForwardedUrl()); System.out.println(" Redirected URL = " + response.getRedirectedUrl()); System.out.println(" Cookies = " + response.getCookies()); }; }
然后把代码里的andDo(print())替换成andDo(prettyPrintResponse())即可。
方法2:全局配置Jackson ObjectMapper
如果希望所有MockMvc的响应都自动格式化,可以在测试配置中定义一个开启缩进的ObjectMapper Bean:
@Configuration public class TestConfig { @Bean public ObjectMapper objectMapper() { return new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); } }
这样MockMvc在序列化响应时会自动使用这个格式化后的ObjectMapper,默认的print()输出也会变成结构化的JSON。
二、让Spring REST Docs生成格式化的JSON文档
这是核心需求——要让生成的API文档里的响应示例是格式化的。Spring REST Docs提供了内置的预处理工具,直接用Preprocessors.prettyPrint()就能搞定:
修改你的测试代码,在document()方法中添加响应预处理:
resultActions = mockMvc.perform(get(urlTemplate, urlVariables) .principal(principal) .contentType(APPLICATION_JSON)) .andExpect(status().isOk()) .andDo(print()) .andDo(document("get-by-id", // 文档标识 preprocessResponse(Preprocessors.prettyPrint()), // 启用响应JSON格式化 pathParametersSnippet, // 其他snippet,比如响应字段描述 responseFields( fieldWithPath("id").description("资源ID"), fieldWithPath("name").description("资源名称"), fieldWithPath("report[].name").description("关联报表名称") // 补充其他字段描述 ) ));
preprocessResponse(Preprocessors.prettyPrint())会自动将响应JSON格式化后写入文档,生成的示例就会是缩进清晰的结构了。
为什么之前没生效?
默认情况下,Spring REST Docs不会对响应做格式化处理,它会直接使用MockMvc返回的原始响应内容。所以你需要显式添加这个预处理步骤,告诉文档生成器要格式化JSON。
内容的提问来源于stack exchange,提问作者FreeOnGoo

