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

I have a method:

@implementation SomeClass

- (void)thisMethod:(ObjectA *)objA {
    [APIClient connectToAPIWithCompletionHandler:^(id result){
        if (result) [objA methodOne];
        else [objA methodTwo];
    }];
}

Is it possible to call a method methodOneor methodTwowhen called thisMethod:? Basically, I just want to drown out this method connectToAPIWithCompletionHandler:. I can do this right now using the swizzling connectToAPIWithCompletionHandler:method. But I want to know if there is a better way.

I found a similar question here , but it uses an instance method, whereas in my case it is a class method.

+3
source share
1 answer

Try the following:

- (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];        
}

Please note that I typed this directly in the browser, but I hope that it is close to work.

+2

Source: https://habr.com/ru/post/1654375/


All Articles