10

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.

TechCrunch
  • 2,924
  • 5
  • 45
  • 79

1 Answers1

13

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();
Top-Master
  • 7,611
  • 5
  • 39
  • 71
Mateusz Dymczyk
  • 14,969
  • 10
  • 59
  • 94
  • 1
    getInvocations() gave wrong value in some instances. May be the mock invocation value is not yet updated by the time it is read. I had to put a sleep for a second before reading getInvocations, but sleeping is the last thing I want to write in my tests. – TechCrunch Apr 02 '15 at 04:03
  • @TechCrunch well in that case the only solution I can come up is the one I posted above or some kind of AOP but I think that would be going too far – Mateusz Dymczyk Apr 02 '15 at 04:28
  • 2
    @TechCrunch could you please paste the code that shows when getInvocations() gives wrong value? – Devs love ZenUML Jun 18 '16 at 02:10
  • 1
    I was able to use `getInvocations().size()` to check if the invocation is the == 1 or not. – рüффп Jan 07 '19 at 16:36
  • 3
    is there a way to use mockingDetails.getInvocations to determine how many times a function with certain parameters were called on the mock/spy? – committedandroider May 28 '19 at 01:22
  • @committedandroider - `getInvocations().stream().filter(i -> i...).count()` – ArtOfWarfare Jan 24 '23 at 02:00