繁体   English   中英

如何使用Spring REST Docs将顶级数组记录为响应有效负载

[英]How to document top-level array as response payload with Spring REST Docs

我正在使用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)了解到,如果您记录了顶层数组,则所有字段都将标记为已记录。 因此,如果您只想记录数组,则可以安全地跳过忽略。

PayloadDocumentation subsectionWithPath方法PayloadDocumentation可以与[]一起使用,而不必忽略其余字段:

result.andDo(docHandler.document(
    responseFields(subsectionWithPath("[]").description("A list of objects")
)));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM