How to get String in response body with mockMvc?

+1 vote
26,525 views
asked Nov 20, 2020 by Hitesh Garg (799 points)  

Currently I am testing a @RestController and using the mockMvc to test the endpoint.
I have successfully tested the status but I am unable to validate the response body of the Rest Api.

@Test
public void shouldReturnTheUserDetails() throws Exception {
    mockMvc.perform(get("/api/user")
        .content("{\"name\" : \"testName\"}")
        .andDo(print())
        .andExpect(status().isOk())
        .andExpect(?); // how to validate the  response body
}

The response is

MockHttpServletResponse:
           Status = 202
    Error message = null
          Headers = {Content-Type=[application/json]}
     Content type = application/json
             Body = {"name" : "testName", "age" : 10, "gender" : "M"}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

How do I validate the response that the name, age and gender are correct?

1 Answer

+1 vote
answered Nov 21, 2020 by Rahul Singh (682 points)  
selected Nov 21, 2020 by Hitesh Garg
 
Best answer

So multiple ways to do this validate the expected return using mockMVC are -

@Test
public void shouldReturnTheUserDetails() throws Exception {
    var expectedJson = "{\"name\" : \"testName\", \"age\" : 10, \"gender\" : \"M\"}";

    mockMvc.perform(get("/api/user")
        .content("{\"name\" : \"testName\"}")
        .andDo(print())
        .andExpect(status().isOk())
        .andExpect(content().json(expectedJson));
}

Another way is to use the andReturn() and then validate that -

@Test
public void shouldReturnTheUserDetails() throws Exception {
    var expectedJson = "{\"name\" : \"testName\", \"age\" : 10, \"gender\" : \"M\"}";

    MvcResult result = mockMvc.perform(get("/api/user")
        .content("{\"name\" : \"testName\"}")
        .andDo(print())
        .andExpect(status().isOk())
        .andReturn();

   String actualJson = result.getResponse().getContentAsString();

  Assert.assertEquals(expectedJson, actualJson); // or use any other library for comparison
}
...