Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the number of times a mock is called in Mockito

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.

like image 590
TechCrunch Avatar asked Apr 02 '15 01:04

TechCrunch


People also ask

Which method on expect () is used to count the number of times a method to have been called?

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.

What is PowerMock in Mockito?

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.

What does @mock do in Mockito?

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.

How do you know if mocked method called?

To check if a method was called on a mocked object you can use the Mockito. verify method: Mockito. verify(someMock).


1 Answers

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.


Mockito 1.10+:

Actually after going through the API for version 1.10 I found:

Mockito.mockingDetails(mock).getInvocations();
like image 156
Mateusz Dymczyk Avatar answered Nov 16 '22 00:11

Mateusz Dymczyk