2016-09-23 97 views
0

這是我的控制器類。現在我想寫下使用mockito的以下控制器類的單元測試用例如何使用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"); 
    } 

} 
+0

使用mockmvc爲http://docs.spring.io/spring-security/site/docs/current/reference/html/test-:

最後,你可以使用你的嘲笑構造mockmvc.html – Jens

回答

0

創建由控制器類的實例:

@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))); 
相關問題