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
Introduction. Hamcrest is a framework for writing matcher objects allowing 'match' rules to be defined declaratively. There are a number of situations where matchers are invaluable, such as UI validation or data filtering, but it is in the area of writing flexible tests that matchers are most commonly used.
Hamcrest is a framework that assists writing software tests in the Java programming language. It supports creating customized assertion matchers ('Hamcrest' is an anagram of 'matchers'), allowing match rules to be defined declaratively. These matchers have uses in unit testing frameworks such as JUnit and jMock.
Purpose of the Hamcrest matcher framework. Hamcrest is a widely used framework for unit testing in the Java world. Hamcrest target is to make your tests easier to write and read. For this, it provides additional matcher classes which can be used in test for example written with JUnit.
Matchers along with assertThat were introduced in JUnit 4.4. assertThat provides a way to write clean highly readable assertions, taking advantage of matchers. These matchers are provided by a library called Hamcrest.
JSONArray
is not an array but rather an ArrayList
(i.e., a java.util.List
).
Thus you should not use Matchers.arrayContainingInAnyOrder(...)
but rather Matchers.containsInAnyOrder(...)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With