Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.5k points)

I have simple integration test

    @Test

public void shouldReturnErrorMessageToAdminWhenCreatingUserWithUsedUserName() throws Exception {

    mockMvc.perform(post("/api/users").header("Authorization", base64ForTestUser).contentType(MediaType.APPLICATION_JSON)

            .content("{\"userName\":\"testUserDetails\",\"firstName\":\"xxx\",\"lastName\":\"xxx\",\"password\":\"xxx\"}"))

            .andDo(print())

            .andExpect(status().isBadRequest())

            .andExpect(?);

}

In last line I want to compare string received in response body to expected string

And in response I get:

MockHttpServletResponse:

          Status = 400

   Error message = null

         Headers = {Content-Type=[application/json]}

    Content type = application/json

            Body = "Username already taken"

   Forwarded URL = null

  Redirected URL = null

Tried some tricks with content(), body() but nothing worked.

1 Answer

0 votes
by (46k points)

You can call andReturn() and use the yielded MvcResult object to get the content as a String.

check below:

MvcResult result = mockMvc.perform(post("/api/users").header("Authorization", base64ForTestUser).contentType(MediaType.APPLICATION_JSON)

            .content("{\"userName\":\"testUserDetails\",\"firstName\":\"xxx\",\"lastName\":\"xxx\",\"password\":\"xxx\"}"))

            .andDo(MockMvcResultHandlers.print())

            .andExpect(status().isBadRequest())

            .andReturn();

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

// do what you will

Browse Categories

...