我正在尝试使用 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);
}
}