mockMvc - Test Error Message

Vinchenzo picture Vinchenzo · Aug 13, 2014 · Viewed 25.6k times · Source

Does anybody have any tips, or does anybody know how I can test the "error message" returned by the HTTP response object?

@Autowired
private WebApplicationContext ctx;

private MockMvc mockMvc;

@Before
public void setUp() throws Exception {
    mockMvc = MockMvcBuilders.webAppContextSetup(ctx).build();
}

Response:

MockHttpServletResponse:
              Status = 200
       Error message = null
             Headers = {Content-Type=[application/json;charset=UTF-8]}
        Content type = application/json;charset=UTF-8

Answer

Fabricio Colombo picture Fabricio Colombo · Aug 7, 2015

You can use the method status.reason().

For example:

     @Test
     public void loginWithBadCredentials() {
        this.mockMvc.perform(
                post("/rest/login")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content("{\"username\": \"baduser\", \"password\": \"invalidPassword\"}")
                )
                .andDo(MockMvcResultHandlers.print())
                .andExpect(status().isUnauthorized())
                .andExpect(status().reason(containsString("Bad credentials")))
                .andExpect(unauthenticated());
    }


    MockHttpServletResponse:
                  Status = 401
           Error message = Authentication Failed: Bad credentials
            Content type = null
                    Body = 
           Forwarded URL = null
          Redirected URL = null
                 Cookies = []