1

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

}
4

1 回答 1

3

首先,您似乎缺少对loginForm.getLogin()anduserDao.findByLogin(loginForm.getLogin())和的存根user.getRole().getName()。如果没有这样的存根,在模拟上调用的这些方法将返回一个默认值(即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);

因为否则false返回默认值。

于 2013-02-25T20:46:32.367 回答