spring-restdocs

Optional on response FieldDescriptor not working as expected


I'm having trouble documenting optional response fields with Spring Docs.

My test code:

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()
        )));

My response:

{
  "success" : true
}

The error:

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 Docs documentation states (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.

So what am I doing wrong?


Solution

  • While the message field is marked as optional, REST Docs still wants to document it for you. Part of that documentation is the field's type. The field's missing from the response so REST Docs can't guess it automatically. Instead, you need to tell it using the type method:

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