【发布时间】:2015-05-10 18:12:32
【问题描述】:
我无法使用 spring mvc test 测试页面内容,因为它是空的。
给定最简单的控制器:
@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>
简单list-home.jsp
<p>Welcome</p>
还有测试:
@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 content expected:<Welcome> but was:<>
打印出来的响应如下:
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = /jsp/view/application.jsp
Redirected URL = null
Cookies = []
环境:
- 春季 3.2
- 瓷砖 2
- Java 6
我错过了什么?
注意:代码在 Tomcat 中使用真实浏览器运行。
【问题讨论】:
-
您不能使用 spring mvc 测试来测试 jsp(内容)。如果涉及瓷砖,那就更难了。我没有找到文档链接或来源,但这是不可能的。
-
文档:docs.spring.io/spring-framework/docs/3.2.0.BUILD-SNAPSHOT/… 带有以下行
For the most part everything should work as it does at runtime with the exception of JSP rendering, which is not available outside a Servlet container -
所以 infoq.com/presentations/spring-mvc-test-htmlunit 中的测试过程在 Spring 4.x 之前不可用。我说的对吗?
-
抱歉,链接网址令人困惑。它对 Spring 4 仍然有效。我只是看了一眼 github 上的演示文稿和相关资源。看起来他们并没有真正使用纯 spring mvc 测试来测试 jsp,而是使用(仪器)HtmlUnit 来检查结果。在我看来,这种测试完成了从简单的单元测试到(类似于)系统/集成测试的步骤,因为您通过从外部(HtmlUnit)测试代码来离开代码的内部。
-
要为您的测试找到解决方案,您应该考虑迈出第一步,使用 MockMvcBuilders#standaloneSetup 测试单个控制器。在这里您可以提供一个 ViewResolver(例如 Jackson for json)并检查内容。