可选的响应 FieldDescriptor 未按预期工作

Optional on response FieldDescriptor not working as expected

我在使用 Spring 文档记录可选响应字段时遇到问题。

我的测试代码:

mockMvc.perform(get("/foo").accept(MediaType.APPLICATION_JSON)) 
        .andExpect(status().isOk()) 
        .andDo(document("foo", responseFields( 
            fieldWithPath("success").description("Indicates request successful or not."),
            fieldWithPath("message").description("Message.").optional()
        )));

我的回复:

{
  "success" : true
}

错误:

org.springframework.restdocs.payload.FieldTypeRequiredException: Cannot determine the type of the field 'message' as it is not present in the payload. Please provide a type using FieldDescriptor.type(Object type).

Spring REST 文档文档状态 (https://docs.spring.io/spring-restdocs/docs/2.0.5.RELEASE/reference/html5/#documenting-your-api-request-response-payloads-fields)

Similarly, the test also fails if a documented field is not found in the payload and the field has not been marked as optional.

那我做错了什么?

虽然 message 字段被标记为可选,但 REST Docs 仍希望为您记录它。该文档的一部分是字段的类型。响应中缺少该字段,因此 REST Docs 无法自动猜测它。相反,您需要使用 type 方法告诉它:

fieldWithPath("message").description("Message.").optional().type(JsonFieldType.STRING)