我有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);
}
这是生成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")
)
)
);
}
}
答案 0 :(得分:2)
如果k1
有时可能null
(或缺席)并且有时会有字符串值,则需要将其标记为可选:
fieldWithPath("listName[].k1").description("Text").optional()