mockMvc - Test Error Message

31,370

Solution 1

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 = []

Solution 2

Even simpler:

String error =  mockMvc...
    .andExpect(status().isUnauthorized())
    .andReturn().getResolvedException().getMessage();

assertTrue(StringUtils.contains(error, "Bad credentials"));

Solution 3

This is the solution I found using JsonPath and MockMvc

this.mvc.perform(post(BASE_URL).contentType(MediaType.APPLICATION_JSON).content(responseJson)).andDo(print())
.andExpect(status().is5xxServerError())
.andExpect(jsonPath("$.message", is("There is an error while executing this test request ")));

Hope this helps.

Solution 4

it works for me:

.andExpect( status().reason( "invalid.duplicate" ) )
Share:
31,370
Vinchenzo
Author by

Vinchenzo

Updated on August 19, 2022

Comments

  • Vinchenzo
    Vinchenzo over 1 year

    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
    
  • Yi Doe
    Yi Doe about 4 years
    jsonPath seems to work only when "Body" is not empty, which is true for the above case.
  • Jeremy Caney
    Jeremy Caney almost 4 years
    By itself? Without e.g. .andExpect(status().isUnauthorized()), as proposed in other answers?
  • Admin
    Admin almost 4 years
    it's just a code snippet, please work with other .andExpect( ... )