简体   繁体   English

如何为此控制器类使用Mockito编写单元测试用例

[英]How to write unit test case with mockito for this controller class

This is my controller class. 这是我的控制器类。 Now that i want to write unit test cases for the below controller class using mockito 现在,我想使用Mockito为下面的控制器类编写单元测试用例

can anyone help me out from this? 有人可以帮我吗?

@Controller
public class LoginController {

    @Autowired
    @Qualifier("skillService")
    private SkillService skillService;

    @Autowired
    private SkillReferenceData skillReferenceData;

    @Autowired
    private EmployeeValidator employeeValidator;

    @RequestMapping(value = "/loginview.html", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('ROLE_ANONYMOUS')")
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse respresultonse) throws Exception {
        ModelAndView model = new ModelAndView("login");
        return model;
    }

    @RequestMapping("/login.htm")
    protected ModelAndView onSubmit(@ModelAttribute("userVB") UserVB userVB,
        BindingResult result, HttpServletRequest request,
    HttpServletResponse response) throws Exception {
        return new ModelAndView("login");
    }

}

Create an instance of your Controller class by: 通过以下方式创建Controller类的实例:

@InjectMocks
LoginController loginController;

By using this annotation you can also access and mock your private variables like skillService, skillReferenceData, employeeValidator by using: 通过使用此注释,您还可以使用以下方法访问和模拟您的私有变量,例如skillService,skillReferenceData,employeeValidator。

@Mock(name = "skillService")
SkillService mockSkillService = createMock(SkillService.class);

Don't forget to initialize your Mockito annotations by adding MockitoAnnotations.initMocks(this); 不要忘记通过添加MockitoAnnotations.initMocks(this);来初始化Mockito注释MockitoAnnotations.initMocks(this); before your unit tests. 在单元测试之前。

Finally, you can mock your constructors by using: 最后,您可以使用以下方法来模拟您的构造函数:

Mockito.when(new ModelAndView(any(String.class).thenReturn(null)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM