为什么MockMvc总是返回空内容()?

时间:2016-10-16 05:07:46

标签: java spring spring-boot

我正在尝试用mockMvc测试我的休息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 = []

我猜上面的空“实际”是由

下面的空“Body”引起的
MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {}
     Content type = null
             Body = 
    Forwarded URL = users/1/mobile
   Redirected URL = null
          Cookies = []

我的问题是:

  1. 为什么MockHttpServletResponse's身体是空的;
  2. 如何正确测试API的响应。

2 个答案:

答案 0 :(得分:3)

如果您的操作方法(带有@RequestMapping注释的方法)返回ModelAndView的实例,或者您使用Model,则必须使用MockMvcResultMatchers#model函数对其进行测试:

.andExpect(MockMvcResultMatchers.model().attribute("phone", "iPhone"))
.andExpect(MockMvcResultMatchers.model().size(1))

MockMvcResultMatchers#contnet适用于REST操作方法(带@RequestBody注释的方法)。

要更好地了解测试Spring MVC和Spring REST控制器,请检查以下链接:

答案 1 :(得分:0)

仅添加此错误的另一个原因,这使我花了一整天的时间才发现。我使用perform方法成功地使用了嘲笑和嘲笑类创建了APITest。然后复制代码以提供另一项服务,我开始一遍又一遍地得到一个空的正文。

不过,最终,我还是决定将每个项目中复制的每个类与另一个项目进行比较。我发现的唯一区别是新控制器收到的请求DTO中的@EqualsAndHashCode注释。