受这个问题的启发,我实现了一项增强功能,使原始答案(见下文)变得过时。
如果您使用 1.0.0.BUILD-SNAPSHOT(可从https://repo.spring.io/libs-snapshot https://repo.spring.io/libs-snapshot),您现在可以将字段标记为忽略。忽略字段计数已被记录,但实际上并未出现在文档中。
考虑到您想要分离文档,进行两个文档调用是有意义的。在第一个中,您可以记录公司名称和员工名单。在第二个中,您记录员工数组并将公司名称标记为忽略。
你的测试看起来像这样:
mockMvc.perform(get("/company/5").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(document("company",
responseFields(
fieldWithPath("companyName").description(
"The name of the company"),
fieldWithPath("employee").description(
"An array of the company's employees"))))
.andDo(document("employee",
responseFields(
fieldWithPath("companyName").ignored(),
fieldWithPath("employee[].name").description(
"The name of the employee"),
fieldWithPath("employee[].age").description(
"The age of the employee"))));
您最终会得到两个片段目录,其中一个名为company
和一个名叫employee
。然后您可以使用response-fields.adoc
每个片段。
原答案
当您记录请求或响应时,没有明确支持忽略字段,但我认为您可以通过使用预处理器删除您不想记录的字段来实现您想要的目的。
鉴于您想要分离文档,有两个document
打电话是有道理的。在第一个中,您可以记录公司名称和员工名单。在第二步中,您需要预处理删除公司的请求,然后记录员工数组。
你的测试看起来像这样:
mockMvc.perform(get("/company/5").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(document("company",
responseFields(
fieldWithPath("companyName").description(
"The name of the company"),
fieldWithPath("employee").description(
"An array of the company's employees"))))
.andDo(document("employee",
preprocessResponse(removeCompany()),
responseFields(
fieldWithPath("employee[].name").description(
"The name of the employee"),
fieldWithPath("employee[].age").description(
"The age of the employee"))));
注意使用preprocessResponse
在第二document
call. removeCompany
返回一个使用自定义的预处理器ContentModifier
从响应中删除公司名称:
private OperationPreprocessor removeCompany() {
return new ContentModifyingOperationPreprocessor(new ContentModifier() {
@Override
public byte[] modifyContent(byte[] originalContent, MediaType contentType) {
ObjectMapper objectMapper = new ObjectMapper();
try {
Map<?, ?> map = objectMapper.readValue(originalContent, Map.class);
map.remove("companyName");
return objectMapper.writeValueAsBytes(map);
}
catch (IOException ex) {
return originalContent;
}
}
});
}
您最终会得到两个片段目录,其中一个名为company
和一个名叫employee
。然后您可以使用response-fields.adoc
每个片段。
虽然上述方法可行,但比实际需要的要困难。我已经打开了an issue https://github.com/spring-projects/spring-restdocs/issues/143这样就不再需要修改响应内容的预处理。