1

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!

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • Why do you try to get that information and what do you want to do with it? If you want to test that a method has been invoked a certain number of times you would use something like [this](https://stackoverflow.com/a/14890172). If it fails, you will also see the number of times the method has actually been called. – second Apr 02 '20 at 12:28
  • "Argument passed to Mockito.mockingDetails() should be a mock, but is null!" ..sounds comprehensible (and credible ..as i know mockito) – xerx593 Apr 05 '20 at 00:09
  • ..it should be `Mockito.mockingDetails(myDependency)...` ...which would give you information refering to the "whole mock" (object), if you need information about `doSomething()`, you can issue/iterate [getStubbings()](https://www.javadoc.io/doc/org.mockito/mockito-core/2.2.7/org/mockito/MockingDetails.html#getStubbings()) – xerx593 Apr 05 '20 at 00:16

1 Answers1

0

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.

amseager
  • 5,795
  • 4
  • 24
  • 47