Search code examples
iosunit-testingocmockito

OCMockito get count of invocations on mock


How can one get the count of invocations on a mocked object?

At a particular point in a test I'd like to get the current count of invocations for a certain method, then continue the test and finally validate that the method was invoked one more time.

This would be something like:

[given([mockA interestingMethod]) willReturnInt:5];
<do some work that may call 'interestingMethod' one or two times>
NSInteger count = currentCountOfInvocations([mockA interestingMethod]); //or something similar
<do some more work that [hopefully] calls interesting method one more time>
[verifyCount(mockA, times(count + 1)) interestingMethod];

Solution

  • You can mock anything with a block. So let's use a block to increment our own counter.

    __block NSUInteger interestingMethodCount = 0;
    [given([mockA interestingMethod]) willDo:^id(NSInvocation *invocation) {
        interestingMethodCount += 1;
        return @5;
    }];
    
    <do some work that may call 'interestingMethod' one or two times>
    NSUInteger countAtCheckpoint = interestingMethodCount;
    
    <do some more work that [hopefully] calls 'interestingMethod' one more time>
    assertThat(@(interestingMethodCount), is(equalTo(@(countAtCheckpoint + 1))));