本文介绍了使用Mockito进行Spring控制器测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Mockito测试我的Spring控制器,但是如果不制作所有@Mock,我实际上无法知道如何做到这一点.此外,测试方法返回了NullPointerException,因为它看不到任何用户,实际上也看不到任何用户角色.有办法以某种方式测试我的控制器吗?

I'm trying to test My Spring controllers using Mockito, but I can't actually get how can I do that without making everything @Mock.Moreover test method returns me NullPointerException, as it can see no user and actually no user role at all.Is there a way to test my controllers somehow?

(控制器类)

@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()的存根.如果没有这种存根,则在模拟程序上调用的这些方法将返回默认值(即null).

First off you seem to be missing stubbing for loginForm.getLogin() and userDao.findByLogin(loginForm.getLogin()) and user.getRole().getName(). Without such stubbing, these methods called on a mock will return a default value (i.e. null).

所以您可能要添加:

when(loginForm.getLogin()).thenReturn(login);
when(userDao.findByLogin(login)).thenReturn(user);
when(user.getRole()).thenReturn(role);
when(role.getName()).thenReturn("Admin");

您将需要更改不同测试的返回值.根据用户和角色的实现类,您可以简单地提供实际实例.对于将结果模拟为错误的测试,您需要添加此存根:

You will want to vary the return values for different tests.Depending on your implementation classes for User and Role, you could simply supply real instances.For a test that simulates the result to have errors you'll want to add this stubbing :

when(result.hasErrors()).thenReturn(true);

因为否则将返回默认的false.

since otherwise the default false is returned.

这篇关于使用Mockito进行Spring控制器测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 19:46