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]
mockMvc.perform(get(API_URL))
.andExpect(jsonPath("$", hasSize(4)));
to test that API returns an object containing 2 members:
accepted value: {"foo": "oof", "bar": "rab"}
mockMvc.perform(get(API_URL))
.andExpect(jsonPath("$.*", hasSize(2)));
I'm using Hamcrest version 1.3 and Spring Test 3.2.5.RELEASE
Note:
You need to include hamcrest-library dependency and import static org.hamcrest.Matchers.*;
for hasSize() to work.