33

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?

2
  • 17
    Did you try using a specific number? verify(userService, times(4))...
    – Dan W
    Sep 26, 2012 at 20:44
  • 1
    This comment is actually the best answer.
    – Dan Ortega
    Jul 8, 2022 at 22:30

3 Answers 3

26

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);
1
  • Thanks! The mocking stuff is a little new to me but you helped a lot. And thanks for the quick response! Sep 26, 2012 at 21:31
11

Adding the number of times you are calling the method should also resolve the issue.

verify(aclient, times(2)).someMethod();

0
3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.