Mockito mockingDetails.getInvocations() question

1.3k views Asked by At

What I am trying to do is to print out the number of times that a certain method was called using Mockito.

When I do the following:

 int counter =
    Mockito.mockingDetails(myDependency)
        .getInvocations()
        .size();
System.out.println( counter );

it prints out all the methods invoked on the mock, however, I want to print out the counter for only one specific method, so if I try,

 int counter =
    Mockito.mockingDetails(myDependency.doSomething())
        .getInvocations()
        .size();
System.out.println( counter );

it occurs an error, saying that

Argument passed to Mockito.mockingDetails() should be a mock, but is null!

Does anyone know how to solve this problem? Thanks in advance!

1

There are 1 answers

0
amseager On

You can play with reflection:

MockingDetails mockingDetails = Mockito.mockingDetails(myDependency);

Method doSomethingMethod = mockingDetails.getMockHandler()
    .getMockSettings()
    .getTypeToMock()
    .getMethod("doSomething"); //here you can also pass the arguments of this method

long counter = mockingDetails.getInvocations()
    .stream()
    .filter(invocation -> invocation.getMethod().equals(doSomethingMethod))
    .count();

Note that in order to get an object of Method class, we can't simply call myDependency.getClass().getMethod("doSomething") because in this case getClass() would return Mockito's wrapper class generated in runtime with its own Method objects. So equals in filter would return false later.