You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Spring Rest Docs记录含对象列表的REST API响应?

用Spring Rest Docs + MockMVC记录GET请求的JSON响应

要为你的GET /api/v1/customers/{id}接口生成带响应示例的API文档,结合MockMVC和Spring Rest Docs可以轻松实现。下面是具体的实现步骤和代码示例:


1. 配置测试类

首先确保你的测试类启用Spring Rest Docs的自动配置,指定文档片段的输出目录:

@WebMvcTest(CustomerController.class)
@AutoConfigureRestDocs(outputDir = "target/generated-snippets")
class CustomerControllerTest {

    @Autowired
    private MockMvc mockMvc;

    // 测试方法写在这里
}

2. 编写测试方法记录响应

在测试方法中,通过MockMVC发起请求、验证响应状态,同时用Spring Rest Docs的document方法生成文档片段,包括响应字段描述和自动捕获的响应示例:

@Test
void shouldReturnCustomerDetails() throws Exception {
    mockMvc.perform(get("/api/v1/customers/3b658b39-4264-4995-99d8-90a1672a75a7")
                    .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(document("get-customer-by-id",
                    // 详细描述响应体的每个字段
                    responseFields(
                            fieldWithPath("id").description("客户的唯一UUID标识"),
                            fieldWithPath("name").description("客户的全名"),
                            fieldWithPath("nickname").description("客户的昵称"),
                            fieldWithPath("phones").description("客户的联系电话列表"),
                            fieldWithPath("phones[].id").description("电话记录的唯一UUID标识"),
                            fieldWithPath("phones[].alias").description("电话的别名(例如「个人电话1」)"),
                            fieldWithPath("phones[].countryCode").description("国家代码(例如巴西的55)"),
                            fieldWithPath("phones[].areaCode").description("地区代码(例如米纳斯吉拉斯的34)"),
                            fieldWithPath("phones[].number").description("电话号码")
                    )
            ));
}

3. 自定义响应示例(可选)

如果需要手动指定响应示例(比如模拟截断的字段值、特定场景的响应),可以直接传入预定义的JSON字符串:

@Test
void shouldReturnCustomerDetailsWithCustomExample() throws Exception {
    // 定义你需要的自定义响应示例
    String customResponse = """
            {
                "id": "3b658b39-4264-4995-99d8-90a1672a75a7",
                "name": "Foo",
                "nickname": "Bar",
                "phones": [
                    {
                        "id": "6ca3a963-bacb-4770-a470-5902b4a17b77",
                        "alias": "Personal Phone 1",
                        "countryCode": "55",
                        "areaCode": "34",
                        "number": "99999-9999"
                    },
                    {
                        "id": "f3a3726b-b5f8-4652-a044-7bf3d95a37de",
                        "alias": "Pe..."
                    }
                ]
            }
            """;

    mockMvc.perform(get("/api/v1/customers/3b658b39-4264-4995-99d8-90a1672a75a7")
                    .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(document("get-customer-by-id-custom-example",
                    responseFields(/* 字段描述同上 */),
                    // 传入自定义响应示例
                    responseBody(customResponse)
            ));
}

4. 依赖配置

确保项目中已经引入Spring Rest Docs的MockMVC依赖:

Maven(pom.xml)

<dependency>
    <groupId>org.springframework.restdocs</groupId>
    <artifactId>spring-restdocs-mockmvc</artifactId>
    <scope>test</scope>
</dependency>

Gradle(build.gradle)

testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc'

运行测试后,Spring Rest Docs会在target/generated-snippets目录下生成对应的文档片段,你可以结合Asciidoctor等工具将这些片段构建成最终的HTML/Markdown格式API文档。

内容的提问来源于stack exchange,提问作者Nielsen Martins Gonçalves

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:49:29