首页 > 解决方案 > 如何为 Spring RestDocs 即 MockMvc 的嵌套订单对象指定 FieldDescriptors

问题描述

我有一个嵌套结构,我想用 Spring MockMvc 为其生成一个 RestDoc。我在指定嵌套结构时遇到问题。这是我到目前为止所拥有的,无需指定嵌套对象即可工作。

Customer c = new Customer("John", 30);
Order order = new Order(....);
c.addOrder(order);

{
 "name":"John",
 "age":30,
 "orders": {
 "orderNumber":"12345",
  "quantity":"1",
  "productCode":"CDE-112",
  "productName" :"bicycle"     
}



 ResultActions resultActions = mockMvc.perform(get("/orders/user/{customerId}" ,

 "001022207")
             .contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(status().isOk()).andDo(document("getProductsForUser" ,
                    preprocessRequest(prettyPrint()) ,
                    preprocessResponse(prettyPrint()) ,
                    responseFields(
                            fieldWithPath("name").type(JsonFieldType.STRING).description("The customer name"),
                            fieldWithPath("age").type(JsonFieldType.NUMBER).description("The age of the customer.") ,

不幸的是,我不知道如何为客户包含嵌套订单。

如果有人能帮我弄清楚如何包含嵌套订单的字段描述符,我将不胜感激。

标签: restspring-mvc

解决方案


这是我解决它的方法:

ResultActions resultActions = mockMvc.perform(get("/orders/user/{customerId}","001022207")
        .contentType(MediaType.APPLICATION_JSON_VALUE))
        .andExpect(status().isOk()).andDo(document("getProductsForUser" ,
                preprocessRequest(prettyPrint()) ,
                preprocessResponse(prettyPrint()) ,
                responseFields(         
      fieldWithPath("name").type(JsonFieldType.STRING).description("The customer name"),                            
      fieldWithPath("age").type(JsonFieldType.NUMBER).description("The age of the customer."),
      fieldWithPath("orders.[].orderNumber").description("The ordernumber"),
      fieldWithPath("orders.[].quantity").description("quantity ordered") 

ETC...


推荐阅读