【问题标题】:How to use spring restdocs to document request body that contains a JSON object如何使用 spring restdocs 记录包含 JSON 对象的请求正文
【发布时间】:2018-12-21 09:32:26
【问题描述】:

我正在使用 spring boot 2 来实现 REST API 服务,并想用 restdocs 记录它。

端点

POST /api/tags

带有请求正文

{"name":"Some Tag", "description":"This is Some Tag"}

用于添加创建新标签。我查看了 restdocs 文档,但仍然找不到记录请求正文的 JSON 字段的方法,谁能帮我填写缺失的部分“......”。

TagRequest request = new TagRequest();
request.setName("Some Tag");
request.setDescription("This is Some Tag");
client.post().uri("/api/tags").body(BodyInserters.fromObject(request)).exchange()
        .expectStatus().isOk().expectBody(Integer.class)
        .consumeWith(document("add-tag", ...... )));

【问题讨论】:

    标签: spring-boot spring-restdocs


    【解决方案1】:

    你需要用户requestFields

    client
                    .post().uri("/api/tags")
                    .body(BodyInserters.fromObject(request))
                    .exchange()
                    .expectStatus().isOk()
                    .expectBody(Integer.class)
                    .consumeWith(
                            document("add-tag",
                                    requestFields(
                                            fieldWithPath("name").description("...."),
                                            fieldWithPath("name").description("....")
                                    )
                            )
                    );
    

    这在官方文档中有记录:https://docs.spring.io/spring-restdocs/docs/current/reference/html5/#documenting-your-api-request-response-payloads

    【讨论】:

    • 答案是正确的,特别是在你的情况下,它会如下,requestFields( fieldWithPath("name").description("some_text").type(String.class.getSimpleName()), fieldWithPath("description").description("some_text").type(String.class.getSimpleName()) )
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    相关资源
    最近更新 更多