How to unit test a Spring MVC controller using @PathVariable?

I’d call what you’re after an integration test based on the terminology in the Spring reference manual. How about doing something like:

import static org.springframework.test.web.ModelAndViewAssert.*;

@ContextConfiguration({/* include live config here
    e.g. "file:web/WEB-INF/application-context.xml",
    "file:web/WEB-INF/dispatcher-servlet.xml" */})
public class MyControllerIntegrationTest {

    private ApplicationContext applicationContext;

    private MockHttpServletRequest request;
    private MockHttpServletResponse response;
    private HandlerAdapter handlerAdapter;
    private MyController controller;

    public void setUp() {
       request = new MockHttpServletRequest();
       response = new MockHttpServletResponse();
       handlerAdapter = applicationContext.getBean(HandlerAdapter.class);
       // I could get the controller from the context here
       controller = new MyController();

    public void testDoSomething() throws Exception {
       final ModelAndView mav = handlerAdapter.handle(request, response, 
       assertViewName(mav, "view");
       // assert something

For more information I’ve written a blog entry about integration testing Spring MVC annotations.

Leave a Comment