Why does MockMvc always return empty content()?
If your action methods (methods with @RequestMapping
annotation) return instances of ModelAndView
or you work with Model
, you have to test it using MockMvcResultMatchers#model
function:
.andExpect(MockMvcResultMatchers.model().attribute("phone", "iPhone"))
.andExpect(MockMvcResultMatchers.model().size(1))
MockMvcResultMatchers#content
is appropriate for REST action methods (methods with @RequestBody
annotation).
To have a better understanding about testing Spring MVC and Spring REST controllers check these links:
- Testing of Spring MVC Applications: Forms
- Testing of Spring MVC Applications: REST API
Just adding another reason for this error, that took me a whole day to discover. I successfully created an APITest using mockito and mockmvc class, using the perform method. Then copied the code to produce another service and I started to get an empty body over and over again.
Nonetheless, at the end of the day I decided to compare each copied class from one project to another. The only one difference that I found was the @EqualsAndHashCode
annotation in my request DTO that is received by the new controller.
So, the recommendation is: add the @EqualsAndHashCode
annotation in your DTO classes.