Search code examples
springviewjunitcontrollerspring-junit

How do I use Spring/JUnit to verify a controller is not sending me to a non-existent view?


I'm using Spring 3.1.1.RELEASE and JUnit 4.11. I setup my JUnit tests like so

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:test-context.xml" })
public class MySpringTest 
{
    protected MockHttpServletRequest request;
    protected MockHttpServletResponse response;
    protected MockHttpSession session;

    @Autowired
    protected RequestMappingHandlerAdapter handlerAdapter;

    @Autowired
    protected RequestMappingHandlerMapping handlerMapping;

When testing controllers, I have this line to verify that the view the controller's method is returning is the right view …

import static org.springframework.test.web.ModelAndViewAssert.assertViewName;
...
final ModelAndView mav = submitMyForm(…);
    assertViewName(mav, "folder/myView");
    ...

protected ModelAndView submitMyForm(… params ...) throws Exception {
    request = new MockHttpServletRequest();
    response = new MockHttpServletResponse();
    request.setRequestURI("/myurl");
    request.setMethod("POST");
    request.addParameter("param1", param1);
    ...

    final Object handler = handlerMapping.getHandler(request).getHandler();
    return handlerAdapter.handle(request, response, handler);
} 

My question is, once I verify the view returned my the controller is the expected view, how do I verify it won't result in a 404? The main problem I'm gaving now is testing whether or not the view actually maps to an underlying page in my WAR file.


Solution

  • why don't use spring-mvc-test and do something like this ?

    @Autowired
    private ViewResolver viewResolver;
    

    // code

    View view = viewResolver.resolveViewName(viewName, locale);
    
    //assert view not null
    

    or something like this, in wich you can check both if the view is ok and the returned status (is status 200/404?) (more code here: http://goo.gl/fMqBsl)

    @Test
    public void indexTest() throws Exception {
    
        mockMvc.perform(get("/")).andDo(print())
            .andExpect(handler().handlerType(MainController.class))
            .andExpect(handler().methodName("index"))
            .andExpect(view().name("index"))
            .andExpect(forwardedUrl("/WEB-INF/tiles/template.jsp"))
            .andExpect(status().isOk());
    }