Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check String in response body with mockMvc

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.

like image 551
pbaranski Avatar asked Aug 20 '13 13:08

pbaranski


People also ask

How does MockMvc perform work?

MockMVC class is part of Spring MVC test framework which helps in testing the controllers explicitly starting a Servlet container. In this MockMVC tutorial, we will use it along with Spring boot's WebMvcTest class to execute Junit testcases which tests REST controller methods written for Spring boot 2 hateoas example.

Is MockMvc thread safe?

From a technical point of view MockMvc is not thread-safe and shouldn't be reused. These setters are package private and a MockMvc instance can be acquired only through MockMvcBuilders . Hence you can't manipulte a MockMvc instance afterwards so that it is actually resuable across multiple tests.


1 Answers

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

See 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  
like image 179
Sotirios Delimanolis Avatar answered Sep 18 '22 11:09

Sotirios Delimanolis