Mocking spring controller validator

帅比萌擦擦* 提交于 2019-12-11 03:52:23

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!