Is there a way to verify that a method has been called 'x' amount of 开发者_如何学运维times?
Looking at the test file for OCMock, it seems that you need to have the same number of expect
s as you have calls. So if you call someMethod
three times, you need to do...
[[mock expect] someMethod];
[[mock expect] someMethod];
[[mock expect] someMethod];
...test code...
[mock verify];
This seems ugly though, maybe you can put them in a loop?
I've had success by leveraging the ability to delegate to a block:
OCMStub([mock someMethod]).andDo(^(NSInvocation *invocation)
{ /* block that handles the method invocation */ });
Inside the block, I just increment a callCount
variable, and then assert that it matches the expected number of calls. For example:
- (void)testDoingSomething_shouldCallSomeMethodTwice { id mock = OCMClassMock([MyClass class]); __block int callCount = 0; OCMStub([mock someMethod]).andDo(^(NSInvocation *invocation) { ++callCount; }); // ...exercise code... int expectedNumberOfCalls = 2; XCTAssertEqual(callCount, expectedNumberOfCalls); }
The block should be invoked each time someMethod
is called, so callCount
should always be the same as the number of times the method was actually called.
If you need to check if a method is only called once, you can do it like this
[self.subject doSomething];
OCMVerify([self.mock method]);
OCMReject([self.mock method]);
[self.subject doSomething];
精彩评论