junit 使用Hamcrest Matchers检查JsonPath的输出

4szc88ey  于 12个月前  发布在  其他
关注(0)|答案(4)|浏览(121)

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

soat7uwm

soat7uwm1#

JSONArray不是数组,而是ArrayList(即java.util.List)。
因此,您不应使用以下内容:
Matchers.arrayContainingInAnyOrder(...)
而是:
Matchers.containsInAnyOrder(...)

ugmeyewa

ugmeyewa2#

您应该使用:用途:
(jsonPath("$..id", hasItems(id1,id2))

x759pob2

x759pob23#

您的示例是针对String项的。下面是一个适用于复杂POJO的更广泛的解决方案:

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

请参阅此处的官方文档:https://github.com/json-path/JsonPath

clj7thdc

clj7thdc4#

遇到相同问题,通过以下方式解决

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

相关问题