简体   繁体   English

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

[英]How to format Spring REST Docs in response body with mockMvc

I write my API documentation with Spring REST Docs. 我用Spring REST Docs编写API文档。

Code example: 代码示例:

@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..
}

But the problem is that the result of the test is answered in one line. 但是问题是测试结果只能在一行中回答。 And understanding the structure of the returned data is very difficult. 而且,了解返回数据的结构非常困难。

Response example: 响应示例:

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 = []

Further, I generate documentation from the answer received and in the documentation also unformatted JSON 此外,我根据收到的答案生成文档,并且在文档中还使用未格式化的JSON

What am I doing wrong? 我究竟做错了什么? How to enable formatting for json? 如何启用JSON格式?

If you're not in a position to configure your application to produce pretty-printed responses, you can have REST Docs do it for you prior to them being documented. 如果您无法配置应用程序以生成精美的响应,则可以在记录文档之前让REST文档为您完成。 This is described in the Customizing Requests and Responses section of the documentation: 在文档的“ 定制请求和响应”部分中对此进行了描述:

Preprocessing is configured by calling document with an OperationRequestPreprocessor , and/or an OperationResponsePreprocessor . 通过使用OperationRequestPreprocessor和/或OperationResponsePreprocessor调用文档来配置预处理。 Instances can be obtained using the static preprocessRequest and preprocessResponse methods on Preprocessors . 可以使用Preprocessors上的静态preprocessRequestpreprocessResponse方法获取实例。 For example: 例如:

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

In the case above the request is being preprocessed to remove a Foo header and the response is being preprocessed so that it appears pretty-printed. 在上述情况下,将对请求进行预处理以除去Foo头,并对响应进行预处理,以使其看起来漂亮。

You can try get ResultActions object from mockMvc and than get MockHttpServletResponse object. 您可以尝试从mockMvc获取ResultActions对象,然后尝试获取MockHttpServletResponse对象。 After that you can get all the values of the fields that came in response. 之后,您可以获取作为响应而来的字段的所有值。 In this case, you will not need to parse the string. 在这种情况下,您将不需要解析字符串。

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

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

Also you can transform MockHttpServletResponse object data to json. 您也可以将MockHttpServletResponse对象数据转换为json。 IUf you use Jacson, than write your custom serializer for this object, add it to MockHttpServletResponse and register in ObjectMapper . 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 should extends StdSerializer<MockHttpServletResponse> and override serialize method. CustomSerializer应该扩展StdSerializer<MockHttpServletResponse>并重写serialize方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM