我正试图使用Mockito测试我的Spring控制器,但如果不制作所有@Mock,我实际上无法做到这一点。此外,测试方法返回NullPointerException,因为它看不到任何用户,实际上根本看不到用户角色。有没有办法以某种方式测试我的控制器?
(控制器类(
@Controller
@SessionAttributes("user")
@RequestMapping("/login.htm")
public class LoginController{
@Autowired
private UserDao userDao;
@Autowired
private LoginValidator loginValidator;
public LoginValidator getLoginValidator() {
return loginValidator;
}
public void setLoginValidator(LoginValidator loginValidator) {
this.loginValidator = loginValidator;
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@RequestMapping(method = RequestMethod.GET)
public String getSendEmptyForm(ModelMap model, HttpServletRequest req) {
req.getSession().invalidate();
model.addAttribute("loginForm", new LoginForm());
return "login";
}
@RequestMapping(method = RequestMethod.POST)
public String postSubmittedForm(ModelMap model, @ModelAttribute("loginForm") LoginForm loginForm,
BindingResult result, SessionStatus status) {
//validate form
loginValidator.validate(loginForm, result);
if (result.hasErrors()) {
return "login";
}
User user = userDao.findByLogin(loginForm.getLogin());
model.addAttribute("user", user);
if (user.getRole().getName().equals("Admin")) {
model.addAttribute("usersList", userDao.findAll());
return "viewAllUsersPage";
}
if (user.getRole().getName().equals("User")){
return "userPage";
}
model.addAttribute("error", "Your role is not User or Admin");
return "errorPage";
}
}
我的测试班
@RunWith(MockitoJUnitRunner.class)
public class LoginControllerTest {
@InjectMocks
private LoginController controllerUT = new LoginController();
@Mock
private ModelMap model;
@Mock
private LoginForm loginForm;
@Mock
private BindingResult result;
@Mock
private SessionStatus status;
@Mock
private LoginValidator validator;
@Mock
private UserDao userDao;
@Mock
private User useк;
@Test
public void testSendRedirect(){
final String target = "login";
String nextPage = controllerUT.postSubmittedForm(model, loginForm, result, status);
assertEquals(target, nextPage);
}
}
首先,您似乎缺少了loginForm.getLogin()
、userDao.findByLogin(loginForm.getLogin())
和user.getRole().getName()
的存根。如果没有这种存根,在mock上调用的这些方法将返回默认值(即null
(。
因此,您可能需要添加:
when(loginForm.getLogin()).thenReturn(login);
when(userDao.findByLogin(login)).thenReturn(user);
when(user.getRole()).thenReturn(role);
when(role.getName()).thenReturn("Admin");
您将希望更改不同测试的返回值。根据用户和角色的实现类,您可以简单地提供真实的实例。对于模拟结果出现错误的测试,您需要添加以下存根:
when(result.hasErrors()).thenReturn(true);
因为否则返回默认CCD_ 5。