Check output of JsonPath with Hamcrest Matchers
Asked Answered
P

4

12

I wrote Spring controller Junits. I used JsonPath to fetch all IDs from JSON using ["$..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; Is there any simple way to use jsonPath.

Settings :- hamcrest-all-1.3 jar , json-path-0.9.0.jar, spring-test-4.0.9.jar

Peary answered 4/10, 2016 at 8:28 Comment(0)
M
13

JSONArray is not an array but an ArrayList (i.e., a java.util.List).

Thus you should not use the following:

Matchers.arrayContainingInAnyOrder(...)

But rather:

Matchers.containsInAnyOrder(...).

Misguide answered 4/10, 2016 at 11:44 Comment(0)
P
12

You should use:

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

Pileus answered 9/10, 2017 at 15:0 Comment(2)
Could you provide the exact static import for jsonPath(...) ?Demarcusdemaria
@Demarcusdemaria org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPathBradeord
Y
1

Your example is for String items. Here's a wider solution for complex POJOs:

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

See the official documentation here: https://github.com/json-path/JsonPath

Yaakov answered 13/1, 2021 at 6:14 Comment(0)
S
0

encounter same issue, resolved by below

Matchers.containsInAnyOrder(new String[]{"ID1","ID2","ID3","ID4","ID5"})
Sticker answered 26/7, 2017 at 7:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.