mockMvc - Test Error Message

前端 未结 4 1825
小蘑菇
小蘑菇 2021-02-03 20:29

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

@Autowired
private WebApplicationCont         


        
相关标签:
4条回答
  • 2021-02-03 21:12

    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.

    0 讨论(0)
  • 2021-02-03 21:29

    Even simpler:

    String error =  mockMvc...
        .andExpect(status().isUnauthorized())
        .andReturn().getResolvedException().getMessage();
    
    assertTrue(StringUtils.contains(error, "Bad credentials"));
    
    0 讨论(0)
  • 2021-02-03 21:31

    it works for me:

    .andExpect( status().reason( "invalid.duplicate" ) )
    
    0 讨论(0)
  • 2021-02-03 21:32

    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 = []
    
    0 讨论(0)
提交回复
热议问题