How do I make sure my documentation is up to date

2019-08-16 05:17发布

问题:

I really like the concept of using failed tests to ensure the documentation is up to date. But I don't know how to make it work for nested json. The way Spring REST Docs handles hierarchical payload seems to defeat the purpose:

When documenting fields, the test will fail if an undocumented field is found in the payload. Similarly, the test will also fail if a documented field is not found in the payload and the field has not been marked as optional. For payloads with a hierarchical structure, documenting a field is sufficient for all of its descendants to also be treated as having been documented.

How would you write your tests for nested json so changes to the payload result in a failed test?

Example:

{
car: {
    motor : {
        brand: "Porsche",
        power: "165 kW"
    },

    suspension: {
        type: "automatic"
    }
}

Test:

.andDo(document("mytest", responseFields(
                    fieldWithPath("car").description("the car").type(JsonFieldType.OBJECT),
                    fieldWithPath("car.motor").description("the motor").type(JsonFieldType.OBJECT),
                    fieldWithPath("car.motor.brand").description("the motor brand").type(JsonFieldType.STRING),
                    fieldWithPath("car.suspension").description("the suspension"))))

A test with these response field definitions would pass even though car.motor.power and suspension.type are not defined. Is there a way to make it work? Multiple tests?

回答1:

The intent was to allow people to document all of the fields if they wanted, without forcing them to do so. However, as you have observed, it can lead to a new field in the API being missed. With hindsight, this was probably a mistake.

One way to avoid missing a new field is to only document "leaf" fields. In your example that would be:

  • car.motor.brand
  • car.motor.power
  • suspension.type

You could do this in a separate test if you also wanted to keep the more detailed documentation. Another alternative would be to use something like JsonPath to assert the structure of the payload.

I realise that none of these is ideal so I've opened https://github.com/spring-projects/spring-restdocs/issues/274.