0

如何获得对模拟对象的调用计数?

在测试中的某个特定点,我想获取某个方法的当前调用计数,然后继续测试并最终验证该方法是否被再次调用。

这将是这样的:

[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];
4

1 回答 1

1

你可以用块模拟任何东西。所以让我们使用一个块来增加我们自己的计数器。

__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))));
于 2016-09-03T16:48:10.693 回答