SuhasD
SuhasD

Reputation: 738

Check output of JsonPath with Hamcrest Matchers

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

Upvotes: 12

Views: 21782

Answers (4)

Sam Brannen
Sam Brannen

Reputation: 31177

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(...).

Upvotes: 13

J&#233;r&#233;my L.
J&#233;r&#233;my L.

Reputation: 121

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

Upvotes: 1

Santiago Velez
Santiago Velez

Reputation: 131

You should use:

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

Upvotes: 12

Addo Zhang
Addo Zhang

Reputation: 386

encounter same issue, resolved by below

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

Upvotes: 0

Related Questions