2

I want to unit test this Spring controller method:

@Autowired
private MyValidator validator;

public String register(
    HttpServletRequest request, 
    ModelMap model, 
    Principal principal,
    @PathVariable Plain plain, 
    RedirectAttributes ratts,
    @ModelAttribute @Valid PlainMoreObject pmo, 
    BindingResult result) 
{

    validator.validate(pmo, result);

I'm using JMock. How do I mock the validator in order to test controller by calling

  controller.register(....) ?
Vikdor
  • 23,934
  • 10
  • 61
  • 84
mjgirl
  • 1,214
  • 7
  • 24
  • 42
  • Check this answer: http://stackoverflow.com/questions/2789529/inject-a-mockups-to-a-bean-that-has-autowired-annotations – Markus Dec 07 '12 at 14:37

1 Answers1

0

There is a helper class in Spring called ReflectionTestUtils (link) you can use to inject mocked beans to fields.

@Mock MyValidator validatorMock;
ReflectionTestUtils.setField(controller, "validator", validatorMock);
controller.register(...);
Markus
  • 809
  • 5
  • 10