Skip to content
Advertisement

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.

Advertisement

Answer

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:

Advertisement