如何使用 mockMvc 在响应正文中格式化 Spring REST Docs

How to format Spring REST Docs in response body with mockMvc

我用 Spring REST Docs 编写我的 API 文档。

代码示例:

@Override
public void getById(String urlTemplate, PathParametersSnippet pathParametersSnippet, Object... urlVariables) throws Exception {
    resultActions = mockMvc.perform(get(urlTemplate, urlVariables)
            .principal(principal)
            .contentType(APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(print());

    // do..
}

但问题是测试结果是在一行中回答的。并且理解返回数据的结构是非常困难的。

响应示例:

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {Content-Type=[application/json;charset=UTF-8]}
     Content type = application/json;charset=UTF-8
             Body = {"creator":null,"modifier":null,"modificationTime":null,"creationTime":null,"id":100,"deleted":false,"name":"Name","description":null,"report":[{"creator":"System","modifier":"System","modificationTime":"2019-01-30T14:21:50","creationTime":"2019-01-30T14:21:50","id":1,"name":"Form name","reportType":{"creator":"System","modifier":"System","modificationTime":"2019-01-30T14:21:50","creationTime":"2019-01-30T14:21:50","id":1,"deleted":false,"name":"Raport"},"unmodifiable":true}]}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

此外,我根据收到的答案生成文档,文档中也未格式化 JSON

我做错了什么?如何为 json 启用格式?

您可以尝试从 mockMvc 获取 ResultActions 对象,而不是获取 MockHttpServletResponse 对象。之后,您可以获得响应中的所有字段值。在这种情况下,您将不需要解析字符串。

resultActions = mockMvc.perform(get(urlTemplate, urlVariables)
    .principal(principal)
    .contentType(APPLICATION_JSON))
    .andExpect(status().isOk())
    .andDo(print());

MockHttpServletResponse content = resultActions.andReturn().getResponse();

您还可以将 MockHttpServletResponse 对象数据转换为 json。 IUf 你使用 Jacson,而不是为这个对象编写你的自定义序列化程序,将它添加到 MockHttpServletResponse 并在 ObjectMapper.

中注册
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(MockHttpServletResponse.class, CustomSerializer.class);
mapper.registerModule(module);
String jsonResult = mapper.writeValueAsString(content);

CustomSerializer 应该扩展 StdSerializer<MockHttpServletResponse> 并覆盖 serialize 方法。

如果您无法配置您的应用程序以生成 pretty-printed 响应,您可以让 REST Docs 在记录它们之前为您完成。这在文档的 Customizing Requests and Responses 部分中有描述:

Preprocessing is configured by calling document with an OperationRequestPreprocessor, and/or an OperationResponsePreprocessor. Instances can be obtained using the static preprocessRequest and preprocessResponse methods on Preprocessors. For example:

this.mockMvc.perform(get("/")).andExpect(status().isOk())
    .andDo(document("index", preprocessRequest(removeHeaders("Foo")), 
            preprocessResponse(prettyPrint()))); 

在上述情况下,正在对请求进行预处理以删除 Foo header 并且正在对响应进行预处理以使其显示为 pretty-printed.