Issue
I'm using PowerMockito with Mockito to mock a few static classes. I want to get the number of times a particular mock object is called during run time so that I can use that count in verify times for another mock object.
I need this because, the method I'm testing starts a thread and stops the thread after a second. My mocks are called several times in this 1 second. After the first mock is called, code branches and different mocks can be called. So, I want to compare the count of first mock with the count of other mocks.
This is a legacy code. So I cannot make changes to actual code. I can only change test code.
Solution
There might be an easier solution, since Mockito already gives you the ability to verify the number of invocations of a particular mock using Mockito.verify()
but I haven't found any method to return that count so you could use answers and implement your own counter:
MyClass myObject = mock(MyClass.class);
final int counter = 0;
when(myObject.myMethod()).then(new Answer<Result>() {
@Override
public Result answer(InvocationOnMock invocation) throws Throwable {
counter++;
return myMockResult;
}
});
OR
doAnswer(i -> {
++counter;
return i.callRealMethod();
}).when(myObject).myMethod();
The problem with this solution is that you need to write the above for every method you're mocking.
Mockito 1.10+:
Actually after going through the API for version 1.10
I found:
Mockito.mockingDetails(mock).getInvocations();
Answered By - Mateusz Dymczyk
Answer Checked By - Robin (JavaFixing Admin)