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

标签 spring rest spring-restdocs

我对 SpringRestDoc spring-restdocs-mockmvc 版本 2.0.0.RELEASE 有以下问题

org.springframework.restdocs.snippet.SnippetException:在有效负载中找不到具有以下路径的字段:[listName[].k1]

结果是
Body = {"listName":[{"k1":null},{"k1":"text"}]}

这是其余的服务

@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);
  }

这是生成文档的测试类
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")
          )
        )
    );
  }
}

最佳答案

k1有时可以通过 null (或不存在)并且有时具有字符串值,您需要将其标记为可选:

fieldWithPath("listName[].k1").description("Text").optional()

关于SpringRestDoc SnippetException : Fields with the following paths were not found in the payload:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49364829/

相关文章:

java - 为什么我在这个 Java 动态 Web 项目中看不到任何 main 方法?

java - 监测方法统计

rest - 将验证码 token 放在 REST API 中的最佳位置在哪里

spring-restdocs - 如何在 Spring REST Docs 中使请求参数可选

kotlin - 如何使用Spring Rest文档可视化index.html页面

java - Spring MVC 展示中如何使用 JSON 处理 HTTP 请求?一些需要理解的问题

java - 如何自定义 Spring Boot 嵌入式 Tomcat 线程池?

ruby-on-rails - rails send_data 在使用 POST 发送 Excel 文件时不发送任何内容

java - 如何通过自引用处理实体的 RESTful 响应

java - 无法在 URL 中记录 JSON