JSON 路径没有值

kad*_*ana 2 unit-testing spring-mvc mockito jsonpath mockmvc

如何为以下包含字符串和数组组合的 JSON 编写模拟MVC 测试。

{
  "id":1,
  "firstName":"NPA",
  "lastName":"TAS",
  "mobile":"123454321",
  "email":"ABCD@GMAIL.COM",
  "accounts":[
         {
          "id":1,
          "balance":"$1000",
          "custid":"1",
          "accNbr":"12345"
         }
            ]
}
Run Code Online (Sandbox Code Playgroud)

我的代码:

@Test
        public void testJson() throws Exception {
            mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
            mockMvc.perform(get("/acc/1")
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.accounts.id", Matchers.is(1)))
            .andExpect(jsonPath("$.accounts.balance", Matchers.is("$1000")))
            .andExpect(jsonPath("$.accounts.accNbr", Matchers.is("12345")))
            .andExpect(jsonPath("$.accounts.custid", Matchers.is("1")))
            .andExpect(jsonPath("$.*", Matchers.hasSize(4)));
        }
Run Code Online (Sandbox Code Playgroud)

我得到了例外

JSON 路径“$.accounts.id”没有值,异常:

预期在路径 $ 中找到具有属性 ['accounts'] 的对象,但发现了 'net.minidev.json.JSONArray'。根据 JsonProvider:'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider',这不是 json 对象。

但是,如果我尝试使用 $.accounts[0].id 我会得到异常

JSON 路径“$.accounts[0].id”没有值,异常:

预期在路径 $ 中找到具有属性 ['accounts'] 的对象,但发现了 'net.minidev.json.JSONArray'。根据 JsonProvider:'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider',这不是 json 对象。

Key*_*r00 5

正如 @glytching 和我提到的,有一个数组,它应该与$.accounts[0].id.

如果您仍然遇到问题,我会尝试在控制台打印结果:

MvcResult result = mockMvc.perform(MockMvcRequestBuilders
         .get("/acc/1").accept(MediaType.APPLICATION_JSON)).andReturn();

String content = result.getResponse().getContentAsString();
Run Code Online (Sandbox Code Playgroud)