gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:03:34 27 4
gpt4 key购买 nike

我是 Mockito 和 Junit 的新手。我正在为忘记密码工作流创建测试用例。下面是 Controller 和测试的代码。谁能告诉我应该如何测试 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);

}

最佳答案

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

基本上代替

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.");

这样您就可以验证该方法是否已被调用。

关于java - 当用户不存在时在单元测试用例中模拟 BindingResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44055736/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com