0

Simplist case my controller returns new ModelAndView("hello"). "hello" maps/resolves to (in an xml file) to a jsp, e.g. "hello" may map to WEB-INF/myapp/goodbye.jsp. I would like to write a test for my controller to verify the view name being returned will properly resolve to something. In the event that somewhere, either in the controller or the (I am using tiles to map) spring config that defines the mapping that the view name has not been fat fingered.

    <bean id="tilesConfigurer"
        class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
        <property name="definitions">
            <list>
                <value>/springmvc/tiles-myapp.xml</value>
            </list>
        </property>
    </bean>

<definition name="hello" extends="main">
    <put-attribute name="title" value="Simple App"/>
    <put-attribute name="body" value="/WEB-INF/myapp/goodbye.jsp"/>
  </definition>
4

1 回答 1

1

您可以使用Spring MVC 测试框架来验证目标 JSP 以获得已解析的视图。

以下是参考手册的相关摘录:

Spring MVC Test 建立在spring-test模块中可用的 Servlet API 的熟悉的“模拟”实现之上。这允许执行请求和生成响应,而无需在 Servlet 容器中运行。在大多数情况下,一切都应该像在运行时一样工作,除了 JSP 渲染,它在 Servlet 容器之外不可用。此外,如果您熟悉其MockHttpServletResponse工作原理,您就会知道转发和重定向实际上并未执行。相反,“转发”和“重定向”的 URL 被保存并可以在测试中断言。这意味着如果您使用 JSP,您可以验证请求被转发到的 JSP 页面。

Spring 自己的JavaConfigTests测试套件中使用 JSP 和 Tiles 演示了这样的测试:

@Test
public void tilesDefinitions() throws Exception {
    this.mockMvc.perform(get("/"))
        .andExpect(status().isOk())
        .andExpect(forwardedUrl("/WEB-INF/layouts/standardLayout.jsp"));
}

问候,

山姆

于 2015-07-02T16:05:52.240 回答