views:

2288

answers:

1

I'm migrating a Spring MVC controller to use the newer style annotations, and want to unit test a controller method that validates a command object (see simple example below).

 @RequestMapping(method = RequestMethod.POST)
public String doThing(Command command, BindingResult result,
                    HttpServletRequest request, HttpServletResponse response,
                    Map<String, Object> model){ 
    ThingValidator validator = new ThingValidator();
    validator.validate(command, result);
... other logic here
    }

My problem is I have to call the controller's method in my unit test, and provide mock values to satisfy its signature to exercise the code properly, and I cannot work out how to mock a BindingResult.

In the old style Controller the signature simply took a HttpServletRequest and HttpServletResponse, which were easily mockable, but due to the flexibility of the new annotation style, one has to pass a lot more in via the signature.

How can one mock a Spring BindingResult for use in a unit test??

+3  A: 

BindingResult is an interface so can you not simply pass in one of Springs implementations of that interface?

I don't use annotations in my Spring MVC code but when I want to test the validate method of a validator I just pass in an instance of BindException and then use the values it returns in assertEquals etc.

Mark
Hi Mark,that put me on the right track thanks. Using a BindingResult bindingResult = new BeanPropertyBindingResult(command, "command"); and sticking the command object in the model within my test seemed to sort my test out.
Al Power
That's how I do it too.
Daniel Alexiuc