Mocking spring controller validator
Asked Answered
M

1

3

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(....) ?
Mansour answered 7/12, 2012 at 8:14 Comment(1)
Check this answer: #2790029Babylonian
B
1

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(...);
Babylonian answered 7/12, 2012 at 14:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.