如何使用MockMvc在响应主体中格式化Spring REST Docs

时间:2019-01-30 14:33:41

标签: java spring spring-mvc-test spring-restdocs

我用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格式?

2 个答案:

答案 0 :(得分:3)

如果您无法配置应用程序以生成精美的响应,则可以在记录文档之前让REST文档为您完成。在文档的Customizing Requests and Responses部分中对此进行了描述:

  

通过使用OperationRequestPreprocessor和/或OperationResponsePreprocessor调用文档来配置预处理。可以使用preprocessRequest上的静态preprocessResponsePreprocessors方法获得实例。例如:

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

在上述情况下,正在对请求进行预处理以删除Foo标头,并对响应进行预处理,以使其看起来很漂亮。

答案 1 :(得分:0)

您可以尝试从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。如果您使用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方法。