1

我是 mockito 新手,我想为用户验证进行单元测试。请在下面找到我要执行单元测试的方法:

@RequestMapping(method = RequestMethod.POST, value = "/login")
public ModelAndView validateViewLogin(@ModelAttribute Person person,
        BindingResult result, HttpServletRequest request) {
    ModelAndView mav = new ModelAndView();

    String userName = person.getFirstName();
    String password = person.getPassword();
    boolean isUserValid = false;
    if (userName != null && password != null) {

        isUserValid = userManagerService.validateUserLogin(userName,
                password);

    }
    if (!isUserValid) {

         mav.setViewName("home");
         return mav;
    }
    mav.addObject("isUserValid", isUserValid);
    mav.setViewName("login");
    return mav;
}

正如您在上面看到的,isUserValid 方法返回一个布尔值,而我要测试的方法返回一个 ModelAndView。

请看我下面的单元测试:

 `@Test public void testValidateOk() {


     MockHttpServletRequest request = new MockHttpServletRequest();
     MockHttpServletResponse response = new MockHttpServletResponse();
     Person person = new Person();
     ModelAndView mav = new ModelAndView();
     mav.setViewName("login");

     person.setFirstName("John");
     person.setPassword("123");





    LogInController controller = new LogInController();

    UserManagerServiceImpl mockpdao = mock(UserManagerServiceImpl.class);

    ReflectionTestUtils.setField(controller, "userManagerService", mockpdao);

    // given
     given(controller.validateViewLogin(person, result, request)).willReturn(mav);

    // when
     ModelAndView validateViewLogin=
             controller.validateViewLogin(person, result, request);
    // then
            assertEquals("home", validateViewLogin.getViewName());


}`

当我运行单元测试时,出现以下错误:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: validateUserLogin() 不能返回 ModelAndView validateUserLogin() 应该返回布尔值


如果您不确定为什么会出现上述错误,请继续阅读。由于上述语法的性质,可能会出现以下问题,因为: 1. 此异常可能发生在错误编写的多线程测试中。有关并发测试的限制,请参阅 Mockito 常见问题解答。2. 使用 when(spy.foo()).then() 语法对 spy 进行存根。使用 doReturn|Throw() 系列方法来存根间谍更安全。更多关于 Mockito.spy() 方法的 javadocs。

at com.gemstone.presentation.LogInControllerTest.testValidateOk(LogInControllerTest.java:49)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

有什么想法可以解决这个问题吗?

4

1 回答 1

0

我不熟悉 BDD 风格的 Mockito,但我猜这条线

given(controller.validateViewLogin(person, result, request)).willReturn(mav);

意味着每当validateViewLogin使用指定的人员、结果和请求调用方法时,您都要求控制器返回给定的模型和视图。但是控制器不是模拟的,所以这可能是导致您的错误的原因。相反,您应该做的是指定模拟用户管理器服务的行为方式。

我注意到您正在创建UserManagerServiceImpl班级的模拟。鉴于它以 'Impl' 结尾,我猜想有一个对应的UserManagerService接口可以代替它进行模拟。Mocktio 可以模拟具体的类,但它不能像模拟接口那样简单。因此,如果确实有一个接口,那么为了安全起见,我会模拟它。

您正在使用ReflectionTestUtils. 这可能不是您的错误的原因,但如果您可以这样做,那么我建议您向控制器添加一个公共设置器,以便更安全、更轻松地注入它。

考虑到上述几点,我将编写您的测试,如下所示:

@Test public void validateViewLogin_validLogin_returnsHomePage() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();

    Person person = new Person();
    person.setFirstName("John");
    person.setPassword("123");

    LogInController controller = new LogInController();
    UserManagerService mockUserService = mock(UserManagerService.class);

    // Configure mock user service to accept the person
    when(mockUserService.validateUserLogin("John", "123")).thenReturn(true);

    // Inject mock user service into controller
    controller.setUserManagerService(mockUserService);

    // Attempt the validation
    ModelAndView mav =
        controller.validateViewLogin(person, result, request);

    // Check the result
    assertEquals("home", mav.getViewName());
}

由于我不熟悉 BDD 语法,因此我使用该行配置了模拟

when(mockUserService.validateUserLogin("John", "123")).thenReturn(true);

但我认为这相当于

given(mockUserService.validateUserLogin("John", "123")).willReturn(true);

于 2013-01-22T09:50:38.320 回答