1

This is my controller class. Now that i want to write unit test cases for the below controller class using 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");
    }

}
cagrias
  • 1,847
  • 3
  • 13
  • 24
Ven
  • 11
  • 2
  • use mockmvc for that http://docs.spring.io/spring-security/site/docs/current/reference/html/test-mockmvc.html – Jens Sep 23 '16 at 08:08

1 Answers1

0

Create an instance of your Controller class by:

@InjectMocks
LoginController loginController;

By using this annotation you can also access and mock your private variables like skillService, skillReferenceData, employeeValidator by using:

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

Don't forget to initialize your Mockito annotations by adding MockitoAnnotations.initMocks(this); before your unit tests.

Finally, you can mock your constructors by using:

Mockito.when(new ModelAndView(any(String.class).thenReturn(null)));
cagrias
  • 1,847
  • 3
  • 13
  • 24
  • On your last statement, I don't think Mockito allows you to stub constructor calls – only methods on a mock. More info on stubbing [here](https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#when-T-) and [here](https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#2). – Voicu Feb 13 '20 at 16:13