有没有人有任何提示,或者有人知道我如何测试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发布于 2015-08-07 16:24:26
您可以使用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 = []发布于 2018-10-09 08:22:48
甚至更简单:
String error = mockMvc...
.andExpect(status().isUnauthorized())
.andReturn().getResolvedException().getMessage();
assertTrue(StringUtils.contains(error, "Bad credentials"));发布于 2018-11-19 13:37:37
这是我使用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 ")));希望这能有所帮助。
https://stackoverflow.com/questions/25288930
复制相似问题