Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SpringRestDoc SnippetException: Fields with the following paths were not found in the payload:

I have following problem with SpringRestDoc spring-restdocs-mockmvc version 2.0.0.RELEASE

org.springframework.restdocs.snippet.SnippetException: Fields with the following paths were not found in the payload: [listName[].k1]

The result is Body = {"listName":[{"k1":null},{"k1":"text"}]}

this is the rest service

@EnableAutoConfiguration
@RestController
public class Docs
{
  @GetMapping("/bug")
  public ResponseEntity bug()
  {
    return ResponseEntity.ok(
      new Object()
        {
          public List listName = Arrays.asList(
            new Object(){
              public String k1 = null;
            }
            , new Object(){
              public String k1 = "text";
            }
          );
        }
      );
  }

  public static void main(String[] args) throws Exception
  {
    SpringApplication.run(Docs.class, args);
  }

And this is the test class that generate doc

public class DocsTest
{

  @Rule
  public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation();

  @Autowired
  private ObjectMapper objectMapper;

  @Autowired
  private WebApplicationContext context;

  private MockMvc mockMvc;

  @Before
  public void setup(){
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
        .apply(
          documentationConfiguration(this.restDocumentation)
            .operationPreprocessors()
            .withResponseDefaults(prettyPrint())
        ).build();
  }


  @Test
  public void bug() throws Exception
  {
    mockMvc.perform(
        get("/bug")
    )
    .andDo(MockMvcResultHandlers.print())
    .andDo(
        document(
        "bug"
          , responseFields(
             fieldWithPath("listName[]")   .description("Array")
            , fieldWithPath("listName[].k1").description("Text")
          )
        )
    );
  }
}
like image 861
user2877911 Avatar asked Mar 07 '23 15:03

user2877911


1 Answers

If k1 can sometimes by null (or absent) and sometimes have a string value, you need to mark it as optional:

fieldWithPath("listName[].k1").description("Text").optional()
like image 184
Andy Wilkinson Avatar answered Mar 16 '23 22:03

Andy Wilkinson