7

我无法使用 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
  • 爪哇 6

我错过了什么?

注意:代码在带有真实浏览器的 Tomcat 中运行。

4

1 回答 1

9

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

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

于 2016-06-10T13:38:17.290 回答