Is it possible to count the number of members using JsonPath?
Using spring mvc test I'm testing a controller that generates
{"foo": "oof", "bar": "rab"}
with
standaloneSetup(new FooController(fooService)).build()
.perform(get("/something").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
.andExpect(jsonPath("$.foo").value("oof"))
.andExpect(jsonPath("$.bar").value("rab"));
I'd like to make sure that no other members are present in the generated json. Hopefully by counting them using jsonPath. Is it possible? Alternate solutions are welcome too.
You can also use the methods inside the jsonpath, so instead of
you can do
We can use JsonPath functions like
size()
orlength()
, like this:or simply parsing to
net.minidev.json.JSONObject
and get de size:Indeed, the second approach looks to perform better than the first one. I made a JMH performance test and I get the following results:
The example code can be found here.
Been dealing with this myself today. It doesn't seem like this is implemented in the available assertions. However, there is a method to pass in an
org.hamcrest.Matcher
object. With that you can do something like the following:if you don't have
com.jayway.jsonassert.JsonAssert
on your classpath (which was the case with me), testing in the following way may be a possible workaround:[note: i assumed that the content of the json is always an array]
To test size of array:
jsonPath("$", hasSize(4))
To count members of object:
jsonPath("$.*", hasSize(4))
I.e. to test that API returns an array of 4 items:
accepted value:
[1,2,3,4]
to test that API returns an object containing 2 members:
accepted value:
{"foo": "oof", "bar": "rab"}
I'm using Hamcrest version 1.3 and Spring Test 3.2.5.RELEASE
hasSize(int) javadoc
Note: You need to include hamcrest-library dependency and
import static org.hamcrest.Matchers.*;
for hasSize() to work.