Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

mockito

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?

like image 226
user1071914 Avatar asked Sep 26 '12 20:09

user1071914


3 Answers

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);
like image 132
matt b Avatar answered Nov 14 '22 16:11

matt b


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

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

like image 37
Alaikya Kasireddy Avatar answered Nov 14 '22 16:11

Alaikya Kasireddy


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.

like image 2
Vijay Vepakomma Avatar answered Nov 14 '22 14:11

Vijay Vepakomma