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

时间:2016-09-23 08:05:44

标签: java spring-mvc mockito spring-junit

这是我的控制器类。现在我想使用mockito

为下面的控制器类编写单元测试用例

任何人都可以帮助我解决这个问题吗?

@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");
    }

}

1 个答案:

答案 0 :(得分:0)

通过以下方式创建Controller类的实例:

@InjectMocks
LoginController loginController;

通过使用此注释,您还可以访问和模拟您的私有变量 skillService,skillReferenceData,employeeValidator使用:

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

在单元测试之前添加MockitoAnnotations.initMocks(this);,不要忘记初始化Mockito注释。

最后,您可以使用以下方法模拟构造函数:

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