我正在使用 Spring REST Docs 来记录 REST API。我正在尝试记录以下 API 操作:
GET /subsystems
GET /subsystems/some_name
例如,调用 GET/subsystems/samba
返回以下 JSON 对象:
{
"id": "samba",
"description": "..."
}
您可以使用以下使用 Spring REST Docs 的代码片段来记录此 API 操作:
this.mockMvc.perform(
get("/subsystems/samba").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andDo(
document("subsystem").withResponseFields(
fieldWithPath("id").description("Subsystem name"),
fieldWithPath("description").description("Subsystem description")));
我的问题是第一个操作:调用 GET/subsystems
返回一个 JSON 数组:
[
{
"id" : "samba",
"description" : "..."
},
{ "id" : "ownCloud",
"description" : "..."
},
{ "id" : "ldap",
"description" : "..."
}
]
我在 Spring REST Docs 文档中找不到任何示例来说明如何记录这种结果。我应该怎么做?
最佳答案
这在 Spring Rest Doc 1.0 中是完全可能的
this.mockMvc.perform(
get("/subsystems").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andDo(
document("subsystem").withResponseFields(
fieldWithPath("[].id").description("Subsystem name"),
fieldWithPath("[].description").description("Subsystem description")));
要记录数组本身,请使用
this.mockMvc.perform(
get("/subsystems").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andDo(
document("subsystem").withResponseFields(
fieldWithPath("[]").description("An array of subsystems"),
fieldWithPath("[].id").ignore(),
fieldWithPath("[].description").ignore()));
如果您只想记录数组本身,我忽略了其他两个字段。您也可以结合使用这两种解决方案。
享受吧。
编辑:我从 Andy Wilkinson 那里了解到,如果您记录顶级数组,所有字段都被标记为已记录。因此,如果您只想记录数组,则可以安全地跳过忽略项。
关于java - 如何使用 Spring REST Docs 将顶级数组记录为响应负载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31162140/