Given the following JSON that is returned from a REST call:
{"Statistik Eintraege":
[{"Wert":"1","Anzahl":41},
{"Wert":"","Anzahl":482},
{"Wert":"-3","Anzahl":1},
{"Wert":"-1","Anzahl":3},
{"Wert":"-2","Anzahl":3}],
"Statistik Typ":"BlahStatistik"}
... I want to verify that'Anzahl' of Wert='' is greater than 400 (is in this example: 482).
What I tried in my java integration test is:
.andExpect(jsonPath("$..[?(@.Wert == '')].Anzahl", greaterThan(400)));
The exception:
java.lang.ClassCastException: class net.minidev.json.JSONArray cannot be cast to class java.lang.Comparable (net.minidev.json.JSONArray is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap')
at org.hamcrest.comparator.ComparatorMatcherBuilder$1.compare(ComparatorMatcherBuilder.java:22)
at org.hamcrest.comparator.ComparatorMatcherBuilder$ComparatorMatcher.describeMismatchSafely(ComparatorMatcherBuilder.java:86)
at org.hamcrest.TypeSafeMatcher.describeMismatch(TypeSafeMatcher.java:82)
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:18)
at org.springframework.test.util.JsonPathExpectationsHelper.assertValue(JsonPathExpectationsHelper.java:74)
at org.springframework.test.web.servlet.result.JsonPathResultMatchers.lambda$value$0(JsonPathResultMatchers.java:87)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:196)
at
What else could I try?
The JsonPath operator [?(<expression>)]
selects all elements matching the given expression. Therefore, the result is a json array.
In the example [?(@.Wert == '')]
matches all json nodes with the field Wert
having an empty value. Your json sample has only single item matching the predicate, but in general there could be multiple. To fix you have either to define a more specific expression matching only a single element or to adjust the matcher to work on a collection.
Matching collection:
.andExpect(jsonPath("$..[?(@.Wert == '')].Anzahl", everyItem(greaterThan(400))))