代码之家  ›  专栏  ›  技术社区  ›  Mohamed Ibrahim Elsayed

如何直接从Spring测试MvcResult json响应中检索数据?

  •  2
  • Mohamed Ibrahim Elsayed  · 技术社区  · 7 年前

    MvcResult mvcResult = super.mockMvc.perform(get("url").accept(MediaType.APPLICATION_JSON).headers(basicAuthHeaders()))
                    .andExpect(status().isOk())
                    .andExpect(jsonPath("$[0].id", is(6))).andReturn();
    
    String responseAsString = mvcResult.getResponse().getContentAsString();
    ObjectMapper objectMapper = new ObjectMapper(); // com.fasterxml.jackson.databind.ObjectMapper
    MyResponse myResponse = objectMapper.readValue(responseAsString, MyResponse.class);
    
    if(myResponse.getName().equals("name")) {
        //
        //
    }
    

    我想知道是否有一种更优雅的方法可以直接从 MvcResult 例如 jsonPath 为了匹配?

    2 回复  |  直到 5 年前
        1
  •  11
  •   Mohamed Ibrahim Elsayed    7 年前

    JsonPath 属于 Jayway

    MvcResult mvcResult = super.mockMvc.perform(get("url").accept(MediaType.APPLICATION_JSON).headers(basicAuthHeaders()))
                    .andExpect(status().isOk())
                    .andExpect(jsonPath("$[0].id", is(6))).andReturn();
    
    String response = mvcResult.getResponse().getContentAsString();
    Integer id = JsonPath.parse(response).read("$[0].id");
    
        2
  •  2
  •   Danylo Rosiichuk    7 年前

    不,不幸的是,没有办法做得更优雅。但是,您可以使用 content().json() .andExpect(content().json("{'name': 'name'}")) 或添加所有必需的 .andExpect()

        3
  •  1
  •   gavenkoa    6 年前

    另一种方法是使用 https://github.com/lukas-krecan/JsonUnit#spring

    import static net.javacrumbs.jsonunit.spring.JsonUnitResultMatchers.json;
    ...
    
    this.mockMvc.perform(get("/sample").andExpect(
        json().isEqualTo("{\"result\":{\"string\":\"stringValue\", \"array\":[1, 2, 3],\"decimal\":1.00001}}")
    );
    this.mockMvc.perform(get("/sample").andExpect(
        json().node("result.string2").isAbsent()
    );
    this.mockMvc.perform(get("/sample").andExpect(
        json().node("result.array").when(Option.IGNORING_ARRAY_ORDER).isEqualTo(new int[]{3, 2, 1})
    );
    this.mockMvc.perform(get("/sample").andExpect(
        json().node("result.array").matches(everyItem(lessThanOrEqualTo(valueOf(4))))
    );