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.
Using Verify This is probably the best way to go as Verify is designed for this exact purpose - to verify the number of times a method has been called.
PowerMockito is a PowerMock's extension API to support Mockito. It provides capabilities to work with the Java Reflection API in a simple way to overcome the problems of Mockito, such as the lack of ability to mock final, static or private methods.
Mockito @Mock Annotation We can mock an object using @Mock annotation too. It's useful when we want to use the mocked object at multiple places because we avoid calling mock() method multiple times. The code becomes more readable and we can specify mock object name that will be useful in case of errors.
To check if a method was called on a mocked object you can use the Mockito. verify method: Mockito. verify(someMock).
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 result;
}
});
The problem with this solution is that you need to write the above for every method you're mocking.
Actually after going through the API for version 1.10
I found:
Mockito.mockingDetails(mock).getInvocations();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With