【问题标题】:No value at JSON pathJSON 路径没有值
【发布时间】:2018-05-25 07:48:28
【问题描述】:

如何为下面的字符串和数组组合的 JSON 编写 mockMVC 测试。

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

我的代码:

@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)));
        }

我得到了异常

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

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

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

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

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

【问题讨论】:

  • 因为有一个账户数组。因此,您应该将 $.accounts[0].id 用于数组帐户中的第一个帐户。
  • @KeyMarker00 $.accounts[0].id 也不起作用
  • 如果您在online evaulator 中使用您的问题中提供的 JSON 和此表达式 $.accounts[0].id,那么您得到一个有效的答案,因此最可能的解释是:“ @KeyMarker00 $.accounts[0].id 也不起作用”是get("/acc/1") 生成的 JSON 与您在问题中包含的 JSON 不匹配。我怀疑该端点生成的 actula JSON 可能如下所示:[{"id":1, "firstName":"NPA", ...}] 即一个子文档数组,每个子文档都包含一个帐户 [],而不是一个包含帐户 [] 的单个文档。

标签: unit-testing spring-mvc mockito jsonpath mockmvc


【解决方案1】:

accounts 属性是一个数组,因此:$.accounts.id 必须使用索引器,例如:$.accounts[0].id

来自docs

[<number> (, <number>)]     Array index or indexes

如果您不确定要使用哪个索引,则可以过滤 JSON 并在过滤后的帐户子文档上断言。例如:

  • $.accounts[?(@.id == 1)].balance:返回$1000
  • $.accounts[?(@.accNbr == 12345)].id:返回1
  • ...等

docs 中有更多详细信息,您可以使用JsonPath evaluator 来解决这个问题。

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多