views:

216

answers:

2

I have an annotated controller with a method that expects a model and a binding result

@RequestMapping(method = RequestMethod.POST)
  public ModelAndView submit(@ModelAttribute(“user”) User user, BindingResult bindingResult) {
     //do something
}

How do I test the binding result? If I call the method with a user and a binding result then I'm not testing the binding process. I figure there myst be something that takes a MockHttpServletRequest and returns the model and the binding result, any suggestions?

A: 

Are you trying to test the binding (which happens before this method would be called) or are you trying to test the "submit" handler method?

You can test the binding with something like this:

 @Test
    public void testHandlerMethod() {

        final MockHttpServletRequest request = new MockHttpServletRequest("post", "/...");
        request.setParameter("firstName", "Joe");
        request.setParameter("lastName", "Smith");

        final User user = new User();
        final WebDataBinder binder = new WebDataBinder(user, "user");
        binder.bind(new MutablePropertyValues(request.getParameterMap()));

        final ModelAndView mv = controllerTestInstance.submit(user, binder.getBindingResult());

        // Asserts...

    }
Rob Beardow
That's just what I was looking for, thanks! In my controller I do bunch of registerCustomEditor setup though, so I suppose that should go on a class I can use from both the controller and the test?
albemuth
If you're registering your custom editors in an initBinder method, you can just call that before you call the handler method in the test.
Rob Beardow
A: 

thanks dude really helpful

Miguel de Melo