问题
I have a method:
@implementation SomeClass
- (void)thisMethod:(ObjectA *)objA {
[APIClient connectToAPIWithCompletionHandler:^(id result){
if (result) [objA methodOne];
else [objA methodTwo];
}];
}
Is there a way to verify methodOne
or methodTwo
will be called when thisMethod:
is called? Basically I just want to stub that connectToAPIWithCompletionHandler:
method. Right now I can do this by swizzling connectToAPIWithCompletionHandler:
method. But I want to know if there's better way.
I found similar question here, but it's using instance method while in my case is class method.
回答1:
Try this:
- (void)test_thisMethod {
id mockA = [OCMockObject mockForClass:[ObjectA class]];
id mockClient = [OCMockObject mockForClass:[APIClient class]];
// Use class method mocking on APIClient
[[mockClient expect] andDo:(NSInvocation *invocation) {
void (^completion)(id result) = [invocation getArgumentAtIndexAsObject:2];
completion(nil);
}] connectToAPIWithCompletionHandler:OCMOCK_ANY];
[[mockA expect] methodTwo];
[[SomeClass new] thisMethod:mockA];
[mockA verify];
[mockClient verify];
}
Note that I typed this direct into the browser, but hopefully it's close to working.
来源:https://stackoverflow.com/questions/17694137/how-to-test-if-a-method-of-an-object-is-called-inside-completion-handler-block-u