[英]Mockito verify() fails with "too many actual invocations"
I have a fairly involved test case I am trying to add the following verify() to:我有一个相当复杂的测试用例,我正在尝试将以下 verify() 添加到:
verify(userService).getUserById(anyLong()).setPasswordChangeRequired(eq(Boolean.TRUE));
This fails with this error:这失败并出现此错误:
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:
So I changed it to this:所以我把它改成了这样:
verify(userService, atLeastOnce()).getUserById(anyLong()).setPasswordChangeRequired(eq(Boolean.TRUE));
And now it fails with:现在它失败了:
java.lang.NullPointerException
at test.controllers.AuthenticationControllerMockTest.testLookupsExceeded(AuthenticationControllerMockTest.java:404)
because this is returning null:因为这是返回空值:
verify(userService, atLeastOnce()).getUserById(anyLong())
This seems puzzling - If I use the default (one invocation only), it fails because it's being invoked multiple times, but if I tell it that multiple invocations are OK, it fails because it can't find any invocations!这似乎令人费解 - 如果我使用默认值(仅一次调用),它会失败,因为它被多次调用,但如果我告诉它多次调用是可以的,它会失败,因为它找不到任何调用!
Can anyone help with this?有人能帮忙吗?
It looks like you both want to mock what happens when userService.getUserById()
is called, and also verify that setPasswordChangeRequired(true)
is called on that returned object.看起来你们俩都想模拟调用userService.getUserById()
时发生的情况,并验证setPasswordChangeRequired(true)
在该返回的对象上被调用。
You can accomplish this with something like:您可以通过以下方式完成此操作:
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);
Getting the same error intermittently.间歇性地得到同样的错误。 We found that we added two @Mock
s with the same type in the class by mistake.我们发现我们错误地在类中添加了两个相同类型的@Mock
。
@Mock
SomeClient aClient;
@Mock
SomeClient bClient;
@Test
void test(){
verify(aClient).someMethod(any()); //passes and fails intermittently
}
Removing the second mock fixed the flakiness.删除第二个模拟修复了片状。
Adding the number of times you are calling the method should also resolve the issue.添加调用该方法的次数也应该可以解决该问题。
verify(aclient, times(2)).someMethod();验证(客户端,次(2))。someMethod();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.