Mock BindingResult in unit test case when user does not exist

Viewed 3728

I'm very new to Mockito and Junit. I'm working on creating test case for forgot password workflow. Below is the code for controller and test. Could anyone tell me how should I test on bindingresult?

@RequestMapping(value = "/user/public/forgotPassword", method = RequestMethod.POST)
public ModelAndView sendforgetPasswordLink(@ModelAttribute ForgetPasswordBean forgetPasswordBean,BindingResult result, HttpSession session) {

    BreadCrumbBuilder.addLinktoBreadCrumb(session, new Link(Constants.FORGET_PASSWORD_TITLE, "/user/public/forgotPassword", Constants.GROUP_USER, 0));

    Map<String, String> breadCrumbs = HomePageController.setupInitialBreadCrumbs(session);
    breadCrumbs.put(Constants.FORGET_PASSWORD_TITLE,    "/user/public/forgotPassword"); 
    session.setAttribute(SessionAttributes.BREAD_CRUMBS,breadCrumbs);

    ModelAndView mav = new ModelAndView(); 
    mav.addObject("displayTitle", Constants.FORGET_PASSWORD_TITLE);

    PublicUser user = publicUserService.findPublicUserByEmail(forgetPasswordBean.getEmail().toLowerCase());
    if(user == null) {
        result.reject("email", "An account does not exist for this email.");
        mav.setViewName("publicuser/forgetPassword.jsp");
        return mav;
    }

    String randomId = java.util.UUID.randomUUID().toString();
    user.setTempId(randomId);
    mailService.sendForgetPasswordLink(user);
    publicUserService.savePublicUser(user);
    String msg = "Password reset instructions have been sent to your email.";

    mav.addObject("msg", msg);
    mav.setViewName("message.jsp");
    return mav;
}

This is test I created so far

@Test
public void TestForgetPasswordForNoUserFound() throws Exception {

    final String input_email = "abc@test.com";

    ForgetPasswordBean  forgetPasswordBean = new ForgetPasswordBean();
    forgetPasswordBean.setEmail(input_email);

    PublicUser daoUser = new PublicUser();
    daoUser.setEmail(input_email);

    when(mockPublicUserService.findPublicUserByEmail(input_email)).thenReturn(null);
    when(mockBindingResult.hasErrors()).thenReturn(true);

    final ModelAndView modelAndView = controller.sendforgetPasswordLink(forgetPasswordBean, mockBindingResult, mockHttpSession);
    ModelMap modelMap = modelAndView.getModelMap();


    assertEquals("An account does not exist for this email.", modelMap.get(mockBindingResult));
    assertEquals("publicuser/forgetPassword.jsp", modelAndView.getViewName());
    assertModelAttributeValue(modelAndView, "displayTitle", Constants.FORGET_PASSWORD_TITLE);

}
1 Answers
Related