Mockito verify()失败了"太多的实际调用"

时间:2012-09-26 20:36:56

标签: java mockito

我有一个相当复杂的测试用例我试图将以下verify()添加到:

verify(userService).getUserById(anyLong()).setPasswordChangeRequired(eq(Boolean.TRUE));

此失败并出现此错误:

org.mockito.exceptions.verification.TooManyActualInvocations: 
userService.getUserById(<any>);
Wanted 1 time:
-> at     test.controllers.AuthenticationControllerMockTest.testLookupsExceeded(AuthenticationControllerMockTest.java:404)
But was 4 times. Undesired invocation:

所以我把它改成了这个:

verify(userService, atLeastOnce()).getUserById(anyLong()).setPasswordChangeRequired(eq(Boolean.TRUE));

现在它失败了:

java.lang.NullPointerException
    at test.controllers.AuthenticationControllerMockTest.testLookupsExceeded(AuthenticationControllerMockTest.java:404)

因为它返回null:

verify(userService, atLeastOnce()).getUserById(anyLong())

这看起来很令人费解 - 如果我使用默认值(仅一次调用),它会失败,因为它被多次调用,但是如果我告诉它多次调用都没问题,它会因为无法找到任何调用而失败! / p>

任何人都可以帮忙吗?

2 个答案:

答案 0 :(得分:17)

看起来你们都想模仿调用userService.getUserById()时会发生什么,并且还要验证在返回的对象上调用了setPasswordChangeRequired(true)

您可以通过以下方式完成此任务:

UserService userService = mock(UserService.class);
User user = mock(User.class);
when(userService.getUserById(anyLong())).thenReturn(user);

...

// invoke the method being tested

...

verify(user).setPasswordChangeRequired(true);

答案 1 :(得分:1)

间歇性地出现相同的错误。我们发现我们错误地在类中添加了两个相同类型的@Mock


@Mock
SomeClient aClient;

@Mock
SomeClient bClient;


@Test
void test(){
  verify(aClient).someMethod(any());  //passes and fails intermittently
}

删除第二个模拟修复了片状。