如何使用mockMvc检查响应体中的String [英] How to check String in response body with mockMvc
本文介绍了如何使用mockMvc检查响应体中的String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有简单的集成测试
@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(?);
}
在最后一行中我想比较在响应体中收到的字符串与预期的字符串
In last line I want to compare string received in response body to expected string
作为回应我得到:
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
尝试了一些内容技巧( ),身体()但没有任何效果。
Tried some tricks with content(), body() but nothing worked.
推荐答案
@Sotirios Delimanolis回答做这个工作但是我一直在寻找比较这里的字符串mockMvc断言
@Sotirios Delimanolis answer do the job however I was looking for comparing strings within this mockMvc assertion
所以这里是
.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"
所以这是证明它有效!
这篇关于如何使用mockMvc检查响应体中的String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文