我想测试 spring 控制器的已解析视图名称

I would like to test the resolved view name for a spring controller

我的控制器的简单案例returns 新模型和视图("hello")。 "hello" maps/resolves 到(在 xml 文件中)到 jsp, 例如"hello" 可能映射到 WEB-INF/myapp/goodbye.jsp。 我想为我的控制器编写一个测试来验证返回的视图名称将正确解析为某些内容。如果在某个地方,无论是在控制器中还是在(我正在使用图块进行映射)spring 配置中,该配置定义了视图名称尚未被指认的映射。

    <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>

您可以使用 Spring MVC Test Framework 验证目标 JSP 以获得已解决的视图。

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

Spring MVC Test builds on the familiar "mock" implementations of the Servlet API available in the spring-test module. This allows performing requests and generating responses without the need for running in a Servlet container. 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. Furthermore, if you are familiar with how the MockHttpServletResponse works, you’ll know that forwards and redirects are not actually executed. Instead "forwarded" and "redirected" URLs are saved and can be asserted in tests. This means if you are using JSPs, you can verify the JSP page to which the request was forwarded.

Spring 自己的测试套件中的 JavaConfigTests 用 JSPs 和 Tiles:

演示了这样的测试
@Test
public void tilesDefinitions() throws Exception {
    this.mockMvc.perform(get("/"))
        .andExpect(status().isOk())
        .andExpect(forwardedUrl("/WEB-INF/layouts/standardLayout.jsp"));
}

此致,

山姆