How to test if a method of an object is called inside completion handler block using OCMock?

a 夏天 提交于 2020-01-23 10:48:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!