如何使用 mockMvc 检查响应体中的字符串

新手上路,请多包涵

我有简单的集成测试

@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() 尝试了一些技巧,但没有任何效果。

原文由 pbaranski 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 525
2 个回答

@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"

所以这证明它有效!

原文由 pbaranski 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以调用 andReturn() 并使用返回的 MvcResult 对象将内容获取为 String

见下文:

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

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

原文由 Sotirios Delimanolis 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题