问题 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

6906
2017-08-13 14:31


起源

不 这个 帮助你。 - Ankur Singhal
我很确定 .andExpect(model().hasNoErrors()) 会做的伎俩 - geoand
我可以做任何事情,比如<code> assertEquals(“预期错误信息”,“实际错误信息”)</ code>而不是<code> .andExpect(model()。hasNoErrors())</ code> - Vinchenzo


答案:


您可以使用该方法 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 = []

16
2017-08-07 16:24