我对 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/