如何比较 MockMvc 中的两个 jsonPath 值

Ock*_*Ock 8 jsonpath mockmvc

我正在使用 MockMvc 为我的 spring 应用程序编写测试。假设我的 json 结果将具有以下格式:

{
  "available": true,
  "location": [
    {"ID": 1, "path": "local1"},
    {"ID": 2, "path": "local2"},
    {"ID": 3, "path": "local3"}
    ],
  "firstItem": "local1"
}
Run Code Online (Sandbox Code Playgroud)

我想测试一下,如果$.firstItem属性的值等于$.location[0].path或不等于,实际上它们应该是相等的。我应该在下面的第三个期望中放入哪个期望?

mockMvc.perform(get(url))
                .andExpect(jsonPath("$.available", equalTo(true)))
                .andExpect(jsonPath("$.location", hasSize(3)))
                .andExpect(jsonPath("$.firstItem", ????));
Run Code Online (Sandbox Code Playgroud)

非常感谢您的帮助!

小智 6

我是这个领域的新手,但这对我有用:

mockMvc.perform(get(url))
            .andDo(mvcResult -> {
                String json = mvcResult.getResponse().getContentAsString();
                String a = JsonPath.parse(json).read("$.firstItem").toString();
                String b = JsonPath.parse(json).read("$.location[0].path").toString();
                Assert.isTrue(a.equals(b),"firstItem is different from location[0].path");
            });
Run Code Online (Sandbox Code Playgroud)