#3824·mockito

Update InvocationOnMock to expose the invocation count

Author: etrandafir93Created May 21, 2026Updated May 22, 2026

I have seen this pattern where we need the mock to behave in a way X time, then behave diffferently (say we need it to fail 10 times, then return a stubbed object)

Here's a dummy example of what I usually see in our tests:

java
private final AtomicInteger invocationCount = new AtomicInteger(0);

@Mock
private final Map<String, Integer> mockedObj = new HashMap<>();

@Test
void dummyTest() {
  when(mockedObj.get("foo"))
    .thenAnswer(invocationOnMock -> {
        if (invocationCount.getAndIncrement() < 10)
          throw new RuntimeException("Oupps");
        return 200;
    });

  // ...
}

It'd be awesome if InvocationOnMock would encapsulate and expose the number of invocations, too:

java
when(mockedObj.get("foo"))
  .thenAnswer(invocationOnMock -> {
     if (invocationOnMock.count() < 10)
        throw new RuntimeException("Oupps");
     return 200;
  });