I have a fairly involved test case I am trying to add the following verify() to:
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.
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);
Adding the number of times you are calling the method should also resolve the issue.
verify(aclient, times(2)).someMethod();
Getting the same error intermittently. We found that we added two @Mock
s with the same type in the class by mistake.
@Mock
SomeClient aClient;
@Mock
SomeClient bClient;
@Test
void test(){
verify(aClient).someMethod(any()); //passes and fails intermittently
}
Removing the second mock fixed the flakiness.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With