Testing Spring MVC annotation mappings

前端 未结 2 1010
星月不相逢
星月不相逢 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 08:00

    You could use AnnotationMethodHandlerAdapter and its handle method programmatically. This will resolve the method for the given request and execute it. Unfortunately this is a little indirect. Actually there is a private class called ServletHandlerMethodResolver in AMHA that is responsible for just resolving the method for a given request. I just filed a request for improvement on that topic, as I really would like to see this possible, too.

    In the meantime you could use e.g. EasyMock to create a mock of your controller class, expect the given method to be invoked and hand that mock to handle.

    Controller:

    @Controller
    public class MyController {
    
      @RequestMapping("/users")
      public void foo(HttpServletResponse response) {
    
        // your controller code
      }
    }
    

    Test:

    public class RequestMappingTest {
    
      private MockHttpServletRequest request;
      private MockHttpServletResponse response;
      private MyController controller;
      private AnnotationMethodHandlerAdapter adapter;
    
    
      @Before
      public void setUp() {
    
        controller = EasyMock.createNiceMock(MyController.class);
    
        adapter = new AnnotationMethodHandlerAdapter();
        request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();
      }
    
    
      @Test
      public void testname() throws Exception {
    
        request.setRequestURI("/users");
    
        controller.foo(response);
        EasyMock.expectLastCall().once();
        EasyMock.replay(controller);
    
        adapter.handle(request, response, controller);
    
        EasyMock.verify(controller);
      }
    }
    

    Regards, Ollie

提交回复
热议问题