What is the best way to count method invocations in a Unit Test. Do any of the testing frameworks allow that?
-
Could you elaborate on what you are trying to do? Are you trying to measure code coverage? Performance? Efficiency? – Mark Robinson Oct 08 '11 at 05:29
-
Not really. Just want to check that when I call testXXX() test method, that method foo() on a class is called at least N times. – user855 Oct 08 '11 at 05:33
-
Is this not possible? I know that Mocking frameworks allow me to assert on invocation counts on the Mock objects. Is it not possible to do it on real objects? – user855 Oct 08 '11 at 05:39
7 Answers
It sounds like you may want to be using the .expects(1)
type methods that mock frameworks usually provide.
Using mockito, if you were testing a List and wanted to verify that clear was called 3 times and add was called at least once with these parameters you do the following:
List mock = mock(List.class);
someCodeThatInteractsWithMock();
verify(mock, times(3)).clear();
verify(mock, atLeastOnce()).add(anyObject());
Source - MockitoVsEasyMock

- 27,789
- 26
- 218
- 353

- 3,537
- 3
- 30
- 37
In Mockito you can do something like this:
YourService serviceMock = Mockito.mock(YourService.class);
// code using YourService
// details of all invocations including methods and arguments
Collection<Invocation> invocations = Mockito.mockingDetails(serviceMock).getInvocations();
// just a number of calls of any mock's methods
int numberOfCalls = invocations.size();

- 13,724
- 6
- 60
- 85
-
I found this to be the simplest and most effective method to use, where you have access to the mocked object. – iZian Sep 07 '17 at 08:27
-
Thanks Jakub, its also good because if you inspect the object you can see where and what functions are being called. – Stoffe Mar 09 '18 at 02:38
-
3That gets all the invocations. Should be a way of getting the invocations of a single method, without streaming and filtering that collections and using Reflection to get the `Method` object to `equal` on. Think Sinon's JS API: `stub.callCount` – oligofren Jun 27 '18 at 08:32
Given an example class "RoleRepository" with a single method "getRole(String user)" which would return a role.
Assuming you have declared this object as Mock or Spy and you want to check whether the method getRole(String) is called for once a time.
You would do something like: Mockito.verify(roleRepository, Mockito.times(1)).getRole(Mockito.anyString());
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class RoleRepositoryTest {
@Spy
private RoleRepository roleRepository = new RoleRepository();
@Test
public void test() {
roleRepository.getRole("toto");
Mockito.verify(roleRepository, Mockito.times(1)).getRole(Mockito.anyString());
}
public static class RoleRepository {
public String getRole(String user) {
return "MyRole";
}
}
}

- 2,451
- 1
- 19
- 31
You can count number of method invocation by using interface Answer in Mockito.
ConnectionPool mockedConnectionPool = mock(ConnectionPool.class);
final int[] counter = new int[1];
when(mockedConnectionPool.getConnection()).then(new Answer<Connection>() {
@Override
public Connection answer(InvocationOnMock invocation) throws Throwable {
counter[0]++;
return conn;
}
});
// some your code
assertTrue(counter[0] == 1);

- 147
- 2
- 2
Depending on what methods you want to count, you can create a test config, with a @Before
advice matching your class / package / method:
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class MethodCounterAspect {
private int counter = 0 // or inject the Counter object into this aspect
@Pointcut( "execution( * com.sample.your.package.*.*(..) )" )
public void methodsToCount() {}
@Before("methodsToCount()")
public void execute() throws Throwable {
counter++; // or update the counter injected into this aspect..
}
// get the counter
}
You can use vanilla AspectJ or Spring AOP via above or XML configs if you find it easier.
You can create different pointcuts / aspect if you need to.

- 22,149
- 6
- 70
- 81
-
If you just want to look at the number of invocations this is the way to do it. If you want to verify invocations, mock frameworks generally wrap this pattern for you with assertions. See my answer for the mock version. – case nelson Oct 08 '11 at 17:27
-
the question is "_What is the best way to count method invocations in a Unit Test_". The above will allow you to do just that => **count method invocations in Unit / Integration tests** without polluting tests themselves. – tolitius Oct 08 '11 at 17:31
-
I agree, which is why I voted you up. But in the comments the author asks about asserting on invocation counts for real objects vs mock objects. If he wants to actually test invocations, he should use a mock library because that's what they are built for. – case nelson Oct 08 '11 at 17:34
It sounds like you may want a test spy. See, for example, Mockito.spy().

- 123
- 3
- 12

- 14,018
- 5
- 37
- 49
You've got a few options
1) Add some special code which counts invocations in the function. It will work, but it's not a great solution.
2) After you run your unit tests, check the code coverage. Most coverage tools will count invocations but they are really designed for post-processing.
3) Use a profiler. A profiler will let you count how many times a function is invoked. This is a very manual process so it's not really designed for unit testing.
A better solution would be to check that output is what you expect rather than checking how it works internally.

- 3,135
- 1
- 22
- 37