【问题标题】:Check output of JsonPath with Hamcrest Matchers使用 Hamcrest 匹配器检查 JsonPath 的输出
【发布时间】:2016-10-04 08:28:00
【问题描述】:

我编写了 Spring 控制器 Junits。 我使用 JsonPath 使用 ["$..id"] 从 JSON 中获取所有 ID。

我有以下测试方法:

mockMvc.perform(get(baseURL + "/{Id}/info", ID).session(session))
    .andExpect(status().isOk()) // Success
    .andExpect(jsonPath("$..id").isArray()) // Success
    .andExpect(jsonPath("$..id", Matchers.arrayContainingInAnyOrder(ar))) // Failed
    .andExpect(jsonPath("$", Matchers.hasSize(ar.size()))); // Success

以下是我传递的数据:-

List<String> ar = new ArrayList<String>();
ar.add("ID1");
ar.add("ID2");
ar.add("ID3");
ar.add("ID4");
ar.add("ID5");

我收到失败消息:-

Expected: [<[ID1,ID2,ID3,ID4,ID5]>] in any order
     but: was a net.minidev.json.JSONArray (<["ID1","ID2","ID3","ID4","ID5"]>)

问题是:如何处理带有org.hamcrest.Matchers;的JSONArray有没有简单的方法使用jsonPath

设置:-hamcrest-all-1.3 jarjson-path-0.9.0.jarspring-test-4.0.9.jar

【问题讨论】:

    标签: java junit spring-test hamcrest jsonpath


    【解决方案1】:

    JSONArray 不是数组,而是ArrayList(即java.util.List)。

    因此,您不应使用Matchers.arrayContainingInAnyOrder(...),而应使用Matchers.containsInAnyOrder(...)

    【讨论】:

      【解决方案2】:

      你应该使用:

      (jsonPath("$..id", hasItems(id1,id2))

      【讨论】:

      • 您能否提供jsonPath(...) 的确切静态导入?
      • @kiltek org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath
      【解决方案3】:

      遇到同样的问题,如下解决

      Matchers.containsInAnyOrder(new String[]{"ID1","ID2","ID3","ID4","ID5"})
      

      【讨论】:

        【解决方案4】:

        您的示例适用于字符串项目。下面是针对复杂 POJO 的更广泛的解决方案:

        .andExpect(jsonPath("$.items.[?(@.property in ['" + propertyValue + "'])]",hasSize(1)))
        

        查看官方文档:https://github.com/json-path/JsonPath

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-10-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-04-16
          • 2015-09-15
          相关资源
          最近更新 更多