简体   繁体   English

使用 Hamcrest 匹配器检查 JsonPath 的输出

[英]Check output of JsonPath with Hamcrest Matchers

I wrote Spring controller Junits.我写了 Spring 控制器 Junits。 I used JsonPath to fetch all IDs from JSON using ["$..id"] .我使用 JsonPath 使用["$..id"]从 JSON 中获取所有 ID。

I have following as test method :我有以下作为测试方法:

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

Following is the data that I passed :-以下是我通过的数据:-

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

I got failure message as:-我收到失败消息:-

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

Question is : How to handle JSONArray with org.hamcrest.Matchers;问题是:如何使用org.hamcrest.Matchers;处理 JSONArray org.hamcrest.Matchers; Is there any simple way to use jsonPath .有什么简单的方法可以使用jsonPath

Settings :- hamcrest-all-1.3 jar , json-path-0.9.0.jar , spring-test-4.0.9.jar设置:- hamcrest-all-1.3 jarjson-path-0.9.0.jarspring-test-4.0.9.jar

JSONArray is not an array but rather an ArrayList (ie, a java.util.List ). JSONArray不是数组而是一个ArrayList (即java.util.List )。

Thus you should not use Matchers.arrayContainingInAnyOrder(...) but rather Matchers.containsInAnyOrder(...) .因此,您不应使用Matchers.arrayContainingInAnyOrder(...)而应使用Matchers.containsInAnyOrder(...)

你应该使用:

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

遇到同样的问题,通过以下解决

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

Your example is for String items.您的示例适用于字符串项目。 Here's a wider solution for complex POJOs:这是复杂 POJO 的更广泛的解决方案:

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

See the official documentation here: https://github.com/json-path/JsonPath在这里查看官方文档: https : //github.com/json-path/JsonPath

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM