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

1.2k views Asked by At

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

There are 1 answers

0
Sam Brannen On BEST ANSWER

You can use the Spring MVC Test Framework to verify the target JSP for a resolved view.

Here's a pertinent excerpt from the reference manual:

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.

The JavaConfigTests in Spring's own test suite demonstrate such a test with JSPs and Tiles:

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

Regards,

Sam