Use hasSize to check for Size of JSON Objects in Spring MVC Tests

Posted by Steven

I'm a huge fan of Spring MVC Tests and already wrote some articles about this topic. If you are new to the topic, here's the official Spring documentation. A coworker discovered a features previously unknown to me that allows to test for the size of JSON objects returned by an endpoint like this:

  1. mockMvc.perform(get("/myapp/ressource/1"))
  2. .andExpect(status().isOk())
  3. .andExpect(jsonPath("$[0].date").exists())
  4. .andExpect(jsonPath("$[0].type").value("1"))
  5. .andExpect(jsonPath("$[0].element.list").value(new ArrayList<>()))
  6. .andExpect(jsonPath("$[0]").value("42"))
  7. .andExpect(jsonPath("$[0].element.*", hasSize(2)))
  8. .andExpect(jsonPath("$[0].*", hasSize(3)))
  9. .andExpect(jsonPath("$.*", hasSize(1)));

This code snippet tests a GET call to an endpoint and makes sure that an object of a certain structure is returned (line 1 to 6) by using JsonPath. However, this tests only the returned value of some certain attributes. Changing the endpoint and adding more returned values would not break the test if line 7 to 9 would not exist. The hasSize() assertions in these lines test the size of the JSON objects, i.e. how many attributes or inner objects exist. In my opinion, these assertions have to be added to every MVC test. This brings the attention of the developer to check if every attribute is present in the test and none is missing.


Using hasSize() assertions makes sure that an endpoint is not only tested for some specific attributes, but also for the size of JSON objects. Hence, changes of the structure of a returned JSON object are also tested for.