spring mvc测试中的空内容

spring mvc测试中的空内容,spring,spring-mvc-test,Spring,Spring Mvc Test,我无法使用SpringMVC测试测试页面内容,因为它是空的 给定最简单的控制器: @RequestMapping(value = "/home") public String home(HttpSession session, ModelMap model) { return "home"; } 相关瓷砖配置: <definition name="base.definition" template="/jsp/view/application.jsp"> <put-a

我无法使用SpringMVC测试测试页面内容,因为它是空的

给定最简单的控制器:

@RequestMapping(value = "/home")
public String home(HttpSession session, ModelMap model) {
  return "home";
}
相关瓷砖配置:

<definition name="base.definition" template="/jsp/view/application.jsp">
  <put-attribute name="header" value="/jsp/view/header.jsp" />
  <put-attribute name="menu" value="/jsp/view/menu.jsp" />
  <put-attribute name="title" value="" />
  <put-attribute name="body" value="" />
  <put-attribute name="footer" value="/jsp/view/footer.jsp" />
</definition>
<definition name="home" extends="base.definition">
  <put-attribute name="title" value="Welcome" />
  <put-attribute name="body" value="/jsp/view/home/list-home.jsp" />
</definition>
以及测试:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration()
@ContextConfiguration(classes = WebTestConfig.class)
public class HomeControllerTest {
  @Autowired
  private WebApplicationContext wac;
  private MockMvc mockMvc;

  @Before
  public void _setup() {
    this.mockMvc =   MockMvcBuilders.webAppContextSetup(this.wac).build();
  }

  @Test
  public void home() throws Exception {
    mockMvc.perform(get("/home"))
        .andDo(print())
        .andExpect(status().isOk())
        .andExpect(forwardedUrl("/jsp/view/application.jsp"))
        .andExpect(content().string("Welcome"));
  }
而且它失败了
java.lang.AssertionError:Response内容应为:但为:

打印出的响应如下所示:

MockHttpServletResponse:
              Status = 200
       Error message = null
             Headers = {}
        Content type = null
                Body = 
       Forwarded URL = /jsp/view/application.jsp
      Redirected URL = null
             Cookies = []
环境:

  • 春季3.2
  • 瓷砖2
  • 爪哇6
我错过了什么


注意:代码在Tomcat和real browser中工作。

您无法为JSP页面的内容编写断言,因为JSP页面由servlet容器呈现,而Spring MVC测试不运行servlet容器。您只能验证视图名称是否正确和/或请求是否转发到正确的url


但是,如果使用不需要servlet容器(如Velocity或Thymeleaf)的视图技术,则可以为视图的内容编写断言。

不能使用spring mvc test测试jsp(内容)。如果涉及到瓷砖,就更难了。我找不到文档链接或源代码,但这是不可能的。文档:使用下面的行
,大多数情况下,一切都应该像在运行时一样工作,JSP呈现除外,它在Servlet容器外部不可用,因此在Spring 4.x之前,中介绍的测试过程不可用。我说得对吗?很抱歉,链接url很混乱。它对Spring 4仍然有效。我只是浏览了一下github上的演示和相关资源。看起来他们并没有使用纯SpringMVC测试来真正测试jsp,而是使用(工具)HtmlUnit来检查结果。在我看来,这种测试从简单的单元测试到(类似于)系统/集成测试,因为您通过从外部测试(HtmlUnit)来离开代码的内部,您应该考虑通过使用MOCKMVCuBuffer-SytalAutoUp测试单个控制器来采取第一步。在这里,您可以提供一个ViewResolver(例如Jackson for json)并检查内容。您可以在Thymeleaf上进行扩展吗?
MockHttpServletResponse:
              Status = 200
       Error message = null
             Headers = {}
        Content type = null
                Body = 
       Forwarded URL = /jsp/view/application.jsp
      Redirected URL = null
             Cookies = []