问题

我有简单的集成测试

@Test
public void shouldReturnErrorMessageToAdminWhenCreatingUserWithUsedUserName() throws Exception {
    mockMvc.perform(post("/api/users").header("Authorization", base64ForTestUser).contentType(MediaType.APPLICATION_JSON)
            .content("{\"userName\":\"testUserDetails\",\"firstName\":\"xxx\",\"lastName\":\"xxx\",\"password\":\"xxx\"}"))
            .andDo(print())
            .andExpect(status().isBadRequest())
            .andExpect(?);
}

在最后一行中,我想比较响应体中收到的字符串和期望的字符串

作为回应我得到:

MockHttpServletResponse:
          Status = 400
   Error message = null
         Headers = {Content-Type=[application/json]}
    Content type = application/json
            Body = "Username already taken"
   Forwarded URL = null
  Redirected URL = null

尝试使用content(),body()但没有任何效果。


#1 热门回答(209 赞)

你可以致电andReturn()并使用returnsMvcResult对象获取内容为aString。见下文:

MvcResult result = mockMvc.perform(post("/api/users").header("Authorization", base64ForTestUser).contentType(MediaType.APPLICATION_JSON)
            .content("{\"userName\":\"testUserDetails\",\"firstName\":\"xxx\",\"lastName\":\"xxx\",\"password\":\"xxx\"}"))
            .andDo(print())
            .andExpect(status().isBadRequest())
            .andReturn();

String content = result.getResponse().getContentAsString();
// do what you will

#2 热门回答(65 赞)

@Sotirios Delimanolis回答了这项工作,但我正在寻找比较这个mockMvc断言中的字符串

所以在这里

.andExpect(content().string("\"Username already taken - please try with different username\""));

当然我的断言失败了:

java.lang.AssertionError: Response content expected:
<"Username already taken - please try with different username"> but was:<"Something gone wrong">

因为:

MockHttpServletResponse:
            Body = "Something gone wrong"

所以这证明它有效!


#3 热门回答(37 赞)

Spring MockMvc现在直接支持JSON。所以你只说:

.andExpect(content().json("{'message':'ok'}"));

并且不像字符串比较,它会说"缺少字段xyz"或"消息预期'确定'得到'nok'。

这个方法是在Spring 4.1中引入的。


原文链接