使用Hamcrest Matchers检查JsonPath的输出

时间:2016-10-04 08:28:01

标签: java junit spring-test hamcrest jsonpath

我写了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

4 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分:2)

您应该使用:

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

答案 2 :(得分:0)

遇到同样的问题,由下面解决

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

答案 3 :(得分:0)

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

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

在此处查看官方文档:Slowing down CPU Frequency by imposing memory stress