views:

31

answers:

1

Hi,

I'm unit-testing my SpringMVC (v. 2.5) controllers using code like the following:

public void testParamValidation() {
    MyController controller = new MyController();
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter("foo", "bar");
    request.addParameter("bar", baz");
    ModelAndView mav = controller .handleRequest(request, new MockHttpServletResponse());
    // Do some assertions on mav
}

This controller is a subclass of AbstractCommandController, so the parameters are bound to a command bean, and any binding or validation errors are stored in an object that implements the Errors interface.

I can't seem to find any way to access this Errors from within the test, is this possible?

Thanks, Don

+1  A: 

To test the validator in my controllers I do something like the following. Basically I use a BindException to get access to the errors.

BindException ex = new BindException(commandObject, "commandName");
controller.onBindAndValidate(new MockHttpServletRequest(), commandObject, ex);
assertEquals(1, ex.getErrorCount());
List<ObjectError> errors = (List<ObjectError>)ex.getAllErrors();
assertEquals("INVALID_COMMAND", errors.get(0).getCode());
Mark