java - 如何使用 Spring Rest Docs 记录对象列表
问题描述
我正在使用 Spring Rest Docs 来记录我的 REST API。我在集成测试中使用 mockMVC,我想记录以下 JSON 响应:
GET /api/v1/customers/3b658b39-4264-4995-99d8-90a1672a75a7
{
"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": "Personal Phone 2",
"countryCode": "55",
"areaCode": "34",
"number": "88888-8888"
}
]
}
我如何记录上面的电话列表?您可以使用以下片段,它使用 Spring REST Docs 来记录此 API 操作:
this.mockMvc.perform(
get("/api/v1/customers/3b658b39-4264-4995-99d8-90a1672a75a7")
.accept(APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(document("customer").withResponseFields(
fieldWithPath("id").description("Unique identifier"),
fieldWithPath("name").description("Customer full name"),
fieldWithPath("nickname").description("How the customer wants to be called")));
解决方案
通过数组对象记录嵌套时,可以这样使用:
this.mockMvc.perform(
get("/api/v1/customers/3b658b39-4264-4995-99d8-90a1672a75a7")
.accept(APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(document("customer").withResponseFields(
fieldWithPath("id").description("Unique identifier"),
fieldWithPath("name").description("Customer full name"),
fieldWithPath("nickname").description("How the customer wants to be called"),
fieldWithPath("phones[].id").description("PHONE ID DESCRIPTION"),
fieldWithPath("phones[].alias").description("PHONE ALIAS DESCRIPTION"),
fieldWithPath("phones[].countryCode").description("PHONE COUNTRY CODE DESCRIPTION"),
fieldWithPath("phones[].areaCode").description("PHONE AREA CODE DESCRIPTION")
fieldWithPath("phones[].number").description("PHONE NUMBER DESCRIPTION")
));
推荐阅读
- c - 在 CS50 可读性问题中获得意外结果
- gmail - 第三方访问“只读”Gmail 范围内的附件
- vue.js - 无法在 vue 中安装 vue chart.js
- node.js - 正在变异的道具:“isOpen”
- ios - 到 testflight 的 Flutter Archive 应用程序给出错误 ITMS-90338:非公共 API 使用
- sql - 如何根据两个不同的标准计算不同的值?
- python - 基于单个数据源更新多个 Qt 模型
- sql - 三个表的 SQL 棘手的左连接 - 所有不同的键
- vue.js - VueJs - 使用 Slot 名称调用另一个组件中的组件
- android - 如何使用 kotlin 删除 view-pager 2 中的项目?