【问题标题】:How to write unit test case with mockito for this controller class如何使用 mockito 为这个控制器类编写单元测试用例
【发布时间】:2016-09-23 08:05:43
【问题描述】:

这是我的控制器类。现在我想使用 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");
    }

}

【问题讨论】:

标签: java spring-mvc mockito spring-junit


【解决方案1】:

通过以下方式创建 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)));

【讨论】:

  • 在你最后的陈述中,我不认为 Mockito 允许你存根构造函数调用——只有模拟上的方法。有关存根 herehere 的更多信息。
猜你喜欢
  • 1970-01-01
  • 2019-11-05
  • 2010-09-12
  • 1970-01-01
  • 1970-01-01
  • 2020-10-28
  • 1970-01-01
  • 1970-01-01
  • 2017-09-06
相关资源
最近更新 更多