我编写了 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 jar
、json-path-0.9.0.jar
、spring-test-4.0.9.jar
JSONArray
不是数组,而是 ArrayList
(即 java.util.List
)。
因此您不应使用以下内容:
Matchers.arrayContainingInAnyOrder(...)
而是:
Matchers.containsInAnyOrder(...)
.
您应该使用:
(jsonPath("$..id", hasItems(id1,id2))
您的示例适用于字符串项目。这是针对复杂 POJO 的更广泛的解决方案:
.andExpect(jsonPath("$.items.[?(@.property in ['" + propertyValue + "'])]",hasSize(1)))
请参阅此处的官方文档:https://github.com/json-path/JsonPath
遇到同样的问题,通过以下解决
Matchers.containsInAnyOrder(new String[]{"ID1","ID2","ID3","ID4","ID5"})