Mockito verify() fails with "too many actual invocations"

Getting the same error intermittently. We found that we added two @Mocks 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.


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();

Tags:

Java

Mockito