spring-boot - 使用 Spring REST Docs 记录空值

标签 spring-boot mockmvc spring-restdocs

假设我们有以下 API:

@RestController
public class PersonController {
    @GetMapping("/api/person")
    public List<Person> findPeople() {
        return Arrays.asList(new Person("Doe", "Foo", "John"), new Person("Doe", null, "Jane"));
    }
}

模型类如下所示:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
    private String lastName;
    private String middleName;
    private String firstName;
}

正如您在 Controller 中看到的,列表中第二个对象的 middleName 属性是 null 。我现在正在尝试使用 Spring REST Docs 来记录 API 的属性,因此我编写了以下测试:

@Test
public void findAllReturnsPeople() throws Exception {
    mockMvc.perform(get("/api/person").accept(MediaType.APPLICATION_JSON))
        .andExpect(jsonPath("$.[0].firstName", is("John")))
        .andExpect(jsonPath("$.[0].middleName", is("Foo")))
        .andExpect(jsonPath("$.[0].lastName", is("Doe")))
        .andExpect(jsonPath("$.[1].firstName", is("Jane")))
        .andExpect(jsonPath("$.[1].middleName", nullValue()))
        .andExpect(jsonPath("$.[1].lastName", is("Doe")))
        .andDo(document("person-get", responseFields(
            fieldWithPath("[].firstName").description("The given name of a person"),
            fieldWithPath("[].middleName").description("The optionally given middle name of a person"),
            fieldWithPath("[].lastName").description("The last- or family name of a person"))));
}

通过使用 responseFields()fieldWithPath() 属性,我试图对每个字段进行描述。但是,这种方法对于中间名失败,抛出以下异常:

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

    at org.springframework.restdocs.payload.AbstractFieldsSnippet.validateFieldDocumentation(AbstractFieldsSnippet.java:257)
    at org.springframework.restdocs.payload.AbstractFieldsSnippet.createModel(AbstractFieldsSnippet.java:167)
    at org.springframework.restdocs.snippet.TemplatedSnippet.document(TemplatedSnippet.java:83)
    at org.springframework.restdocs.generate.RestDocumentationGenerator.handle(RestDocumentationGenerator.java:206)
    at org.springframework.restdocs.mockmvc.RestDocumentationResultHandler.handle(RestDocumentationResultHandler.java:55)
    at org.springframework.test.web.servlet.MockMvc$1.andDo(MockMvc.java:183)
    at be.g00glen00b.apps.demoempty.DemoEmptyApplicationTests.findAllReturnsPeople(DemoEmptyApplicationTests.java:37)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
    at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

但是,当我更改代码并将第二个 Person 对象的中间名更改为 "Bar" 时,错误消失,并且正确生成了代码段。

此外,当我删除 fieldWithPath("[].middleName") 代码并运行测试时,出现以下异常:

org.springframework.restdocs.snippet.SnippetException: The following parts of the payload were not documented:
[ {
  "middleName" : "Foo"
}, {
  "middleName" : null
} ]

这是有道理的,因为在这种情况下没有记录中间名属性。

我的问题是如何防止此错误并记录 middleName 属性的作用?

这是我到目前为止尝试过的:
  • 仅记录非空值,例如 [0].middleName(这会导致相同的异常)
  • 将类型显式更改为 JsonFieldType.STRINGJsonFieldType.VARIES(这也会导致相同的异常)
  • 最佳答案

    您需要告诉 REST Docs 该字段是可选的。您可以通过调用 optional() 上的 FieldDescriptor 方法来完成此操作:

    .andDo(document("person-get", responseFields(
            fieldWithPath("[].firstName").description("The given name of a person"),
            fieldWithPath("[].middleName").description("The optionally given middle name of a person").optional(),
            fieldWithPath("[].lastName").description("The last- or family name of a person"))));
    

    关于spring-boot - 使用 Spring REST Docs 记录空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51078761/

    相关文章:

    java - 如何禁用 undertow 的自动配置

    java - JPA 按两个日期之间的日期查找

    java - 在 Spring Boot Webflux 中生成服务器发送的事件

    unit-testing - JSON 路径没有值

    java - JSONObject 应在路径 $ 中找到属性为 ['XXX' ] 的对象

    java - 如何从 Spring Rest 文档中排除一些测试?

    gradle - 如何将图像添加到REST docs API文档

    java - 如何在Spring Boot aop @Around函数中创建事务?

    spring - HttpRequestMethodNotSupportedException : Request method 'POST' not supported

    java - SpringBoot @WebMvcTest 安全问题