当用户不存在时,在单元测试用例中模拟BindingResult

时间:2017-05-18 18:51:47

标签: java junit mockito

我对Mockito和Junit很新。我正在为忘记密码工作流程创建测试用例。下面是控制器和测试的代码。谁能告诉我如何测试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;
}

这是我到目前为止创建的测试

@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 个答案:

答案 0 :(得分:4)

您可以通过检查是否已调用BindingResult方法来验证reject的行为。

基本上不是

assertEquals("An account does not exist for this email.", modelMap.get(mockBindingResult));

您可以执行以下操作

Mockito.verify(mockBindingResult).reject("email", "An account does not exist for this email.");

通过这种方式,您可以验证方法是否已被调用。