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

SuhasD
  • 728
  • 2
  • 7
  • 20

4 Answers4

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

catch23
  • 17,519
  • 42
  • 144
  • 217
Sam Brannen
  • 29,611
  • 5
  • 104
  • 136
10

You should use:

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

Santiago Velez
  • 111
  • 1
  • 7
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

0

encounter same issue, resolved by below

Matchers.containsInAnyOrder(new String[]{"ID1","ID2","ID3","ID4","ID5"})
Addo Zhang
  • 356
  • 3
  • 8