代码之家  ›  专栏  ›  技术社区  ›  takacsot

春季mvc测试中的空内容

  •  7
  • takacsot  · 技术社区  · 9 年前

    我无法用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>
    

    易于理解的 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和真实浏览器中运行。

    1 回复  |  直到 9 年前
        1
  •  9
  •   pkainulainen    8 年前

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

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