问题
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(....) ?
回答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(...);
来源:https://stackoverflow.com/questions/13759292/mocking-spring-controller-validator