我正在尝试使用 mockMvc 测试我的 rest api。
mockMvc.perform(get("/users/1/mobile")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(print())
.andExpect(content().string("iPhone"))
测试失败是因为:
java.lang.AssertionError: Response content
Expected :iPhone
Actual :
从 print()
的输出中,我可以知道 API 实际上返回了预期的字符串“iPhone”。
ModelAndView:
View name = users/1/mobile
View = null
Attribute = treeNode
value = "iPhone"
errors = []
我猜上面的空“Actual”是由下面的空“Body”引起的
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = users/1/mobile
Redirected URL = null
Cookies = []
我的问题是:
- 为什么
MockHttpServletResponse 的
Body 是空的; - 如何正确测试 API 的响应。
最佳答案
如果您的操作方法(带有 @RequestMapping
注释的方法)返回 ModelAndView
的实例或者您使用 Model
,则必须对其进行测试使用 MockMvcResultMatchers#model
功能:
.andExpect(MockMvcResultMatchers.model().attribute("phone", "iPhone"))
.andExpect(MockMvcResultMatchers.model().size(1))
MockMvcResultMatchers#content
适用于 REST 操作方法(带有 @RequestBody
注释的方法)。
要更好地了解测试 Spring MVC 和 Spring REST Controller ,请查看以下链接:
关于java - 为什么 MockMvc 总是返回空的 content()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40067068/