Announcement Announcement Module
Collapse
No announcement yet.
Base Unit Test for Controllers? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Base Unit Test for Controllers?

    Is there a base class that I should be using for testing controllers (looking in org.springframework.test but I'm not seeing anything geared towards controller testing) or should I be writing my own using XmlWebApplicationContext or some such context? Any other tips pertaining to controller testing would be appreciated, as well.

    Thanks,

    Ryan

  • #2
    Take a look at MockHttpServletRequest and MockHttpServletResponse in spring-mock.jar

    There are a few options for testing. For integration tests, you can use AbstractDependencyInjectionSpringContextTests.

    To test a smaller scope which is often pereferable, you can insert mocks (e.g. using EasyMock) for your services layer.

    Here's an incomplete mock example:
    Code:
            //Add request data
            request = new MockHttpServletRequest("POST", "/");
            response = new MockHttpServletResponse();
    
            request.addParameter("formInputName", "formValue");
            ...
    
            //MockControl.createControl(MyService.class); in setUp
            //Add mock behaviour
            ....
            mc.setThrowable(new DuplicateException("mock"));
            mc.replay();
    
            //Now test controller
            ModelAndView mv = myController.handleRequest(request, response);
            BindException errors = (BindException) mv.getModel().get(BindException.ERROR_KEY_PREFIX+"command");
            
            assertNotNull(errors);
    And don't forget mc.verify() in your teardown.

    Comment

    Working...
    X