mockMvc - 测试错误消息

时间:2014-08-13 14:31:14

标签: spring-mvc mockmvc

是否有人有任何提示,或者有人知道如何测试HTTP响应对象返回的“错误消息”吗?

@Autowired
private WebApplicationContext ctx;

private MockMvc mockMvc;

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

响应:

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

4 个答案:

答案 0 :(得分:24)

您可以使用方法status.reason()

例如:

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

答案 1 :(得分:0)

更简单:

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

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

答案 2 :(得分:0)

这是我使用JsonPath和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 ")));

希望这会有所帮助。

答案 3 :(得分:0)

对我有用:

.andExpect( status().reason( "invalid.duplicate" ) )