How to unit test a Spring MVC annotated controller?

后端 未结 3 1336
陌清茗
陌清茗 2020-12-24 03:41

I am following a Spring 2.5 tutorial and trying, at the same time, updating the code/setup to Spring 3.0.

In Spring 2.5 I had the HelloControlle

相关标签:
3条回答
  • 2020-12-24 04:04

    You can also look into other web testing frameworks that are independent of Spring like HtmlUnit, or Selenium. You won't find any more robust strategy with JUnit alone other than what Sasha has described, except you should definitely assert the model.

    0 讨论(0)
  • 2020-12-24 04:18

    One advantage of annotation-based Spring MVC is that they can be tested in a straightforward manner, like so:

    import org.junit.Test;
    import org.junit.Assert;
    import org.springframework.web.servlet.ModelAndView;
    
    public class HelloControllerTest {
       @Test
       public void testHelloController() {
           HelloController c= new HelloController();
           ModelAndView mav= c.handleRequest();
           Assert.assertEquals("hello", mav.getViewName());
           ...
       }
    }
    

    Is there any problem with this approach?

    For more advanced integration testing, there is a reference in Spring documentation to the org.springframework.mock.web.

    0 讨论(0)
  • 2020-12-24 04:22

    With mvc:annotation-driven you have to have 2 steps: first you resolve the request to handler using HandlerMapping, then you can execute the method using that handler via HandlerAdapter. Something like:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("yourContext.xml")
    public class ControllerTest {
    
        @Autowired
        private RequestMappingHandlerAdapter handlerAdapter;
    
        @Autowired
        private RequestMappingHandlerMapping handlerMapping;
    
        @Test
        public void testController() throws Exception {
            MockHttpServletRequest request = new MockHttpServletRequest();
            // request init here
    
            MockHttpServletResponse response = new MockHttpServletResponse();
            Object handler = handlerMapping.getHandler(request).getHandler();
            ModelAndView modelAndView = handlerAdapter.handle(request, response, handler);
    
            // modelAndView and/or response asserts here
        }
    }
    

    This works with Spring 3.1, but I guess some variant of this must exist for every version. Looking at the Spring 3.0 code, I'd say DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter should do the trick.

    0 讨论(0)
提交回复
热议问题