Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Mockito verify total number of method calls on a mocked Object?

Mockito's verify can assert a certain number of interactions with a method on a mocked object occurred.

// Given
SomeService someService = mock(SomeService.class);

// When
someService.prepare();
someService.prepare();

// Then
verify(someService, times(2)).prepare(); // test passes

Sometimes it is useful in unit tests to know that the total number of method invocations on a mocked object has not changed.

This provides visibility (i.e. a failing test) when new method invocations are added.

Does Mockito provide this functionality?

In certain situations I'd want to call:

verify(someService, times(2));

..without getting an UnfinishedVerificationException:

org.mockito.exceptions.misusing.UnfinishedVerificationException: 
Missing method call for verify(mock)...

Example of correct verification:
  verify(mock).doSomething()
like image 966
alexvinall Avatar asked Jun 08 '15 12:06

alexvinall


1 Answers

There's no API for that at that time. You can try to code your own verifier code using MockingDetails.getInvocations

Mockito.mockingDetails(mock).getInvocations()
like image 66
Brice Avatar answered Nov 15 '22 14:11

Brice