How can I get invocations per method from a Mockito mock?

Viewed 480

I want to get a number of invocations per a given method from a Mockito mock.

Lets say I declared a mock and two stubbing for it:

when(mock.methodA()).thenReturn(..);
when(mock.methodB()).thenReturn(..);

I can do something like Mockito.mockingDetails(mock).getInvocations() but it returns a collection of all invocations. I want to get a number of invocations for the methodA only.

2 Answers

Try to use verify(), for example:

verify(mock, times(N)).methodA();
verify(mock, times(N)).methodB();

when N check for invocation numbers.

For getting data about specific method only use thats:

 new DefaultMockingDetails(service).getInvocations()
                    .stream()
                    .map(InvocationOnMock::getMethod)
                    .filter(s -> s.getName().equals("methodName"))
                    .collect(toList())

this method will return Collection invocations for that mock.

for more info see here

I think I overlooked that the Invocation object has a getMethod property inherited from the superclass InvocationOnMock. Therefore it is possible to do something like:

Mockito.mockingDetails(mock).getInvocations().stream()
                        .map(InvocationOnMock::getMethod)
                        .map(Method::getName)
                        .filter(methodName -> methodName.equals("methodA"))

Not super neat but does the job.

Related