'Why does MockMvc always return empty content()?

I'm trying to test my rest api with mockMvc.

mockMvc.perform(get("/users/1/mobile")
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andDo(print())
        .andExpect(content().string("iPhone"))

The test failed because of:

java.lang.AssertionError: Response content 
Expected :iPhone
Actual   :

From the output of print(), I can know the API actually returned the expected string "iPhone".

ModelAndView:
        View name = users/1/mobile
             View = null
        Attribute = treeNode
            value = "iPhone"
           errors = []

And I guess the empty "Actual" above is caused by empty "Body" below

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {}
     Content type = null
             Body = 
    Forwarded URL = users/1/mobile
   Redirected URL = null
          Cookies = []

My questions are:

  1. Why MockHttpServletResponse's Body is empty;
  2. How can I correctly test the response of API.


Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1