Testing Spring MVC annotation mappings

前端 未结 2 1012
星月不相逢
星月不相逢 2020-12-13 07:41

With Spring MVC, you can specify that a particular URL will handled by a particular method, and you can specify that particular parameters will map to particular arguments,

2条回答
  •  一个人的身影
    2020-12-13 07:52

    Ollie's solution covers testing the specific example of an annotation but what about the wider question of how to test all the other various Spring MVC annotations. My approach (that can be easily extended to other annotations) would be

    import static org.springframework.test.web.ModelAndViewAssert.*;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration({/* include live config here
        e.g. "file:web/WEB-INF/application-context.xml",
        "file:web/WEB-INF/dispatcher-servlet.xml" */})
    public class MyControllerIntegrationTest {
    
        @Inject
        private ApplicationContext applicationContext;
    
        private MockHttpServletRequest request;
        private MockHttpServletResponse response;
        private HandlerAdapter handlerAdapter;
        private MyController controller;
    
        @Before
        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();
        }
    
        @Test
        public void testFoo() throws Exception {
           request.setRequestURI("/users");
           final ModelAndView mav = handlerAdapter.handle(request, response, 
               controller);
           assertViewName(mav, null);
           assertAndReturnModelAttributeOfType(mav, "image", Image.class);
        }
    }
    

    I've also written a blog entry about integration testing Spring MVC annotations.

提交回复
热议问题