javaspringtestingjsonpathspring-test-mvc

How to count members with jsonpath?


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.


Solution

  • 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

    hasSize(int) javadoc

    Note: You need to include hamcrest-library dependency and import static org.hamcrest.Matchers.*; for hasSize() to work.