mockMvc - Test Error Message

我是研究僧i 提交于 2019-12-05 10:51:42

问题


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

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



回答2:


Even simpler:

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

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



回答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.



来源:https://stackoverflow.com/questions/25288930/mockmvc-test-error-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!