小编kad*_*ana的帖子

JSON 路径没有值

如何为以下包含字符串和数组组合的 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 对象。

unit-testing spring-mvc mockito jsonpath mockmvc

2
推荐指数
1
解决办法
7211
查看次数

标签 统计

jsonpath ×1

mockito ×1

mockmvc ×1

spring-mvc ×1

unit-testing ×1