5

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.

Community
  • 1
  • 1
Nico Prananta
  • 474
  • 4
  • 14

1 Answers1

3

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.

Ben Flynn
  • 18,524
  • 20
  • 97
  • 142
  • thanks! it works! I just want to confirm my understanding, so for class method, the mock object doesn't have to be "fed" to the tested method. While instance method needs to be "fed" to the tested method. Is it like that? – Nico Prananta Jul 18 '13 at 02:22
  • Yes, that's a good way of thinking of it. The syntax OCMock uses is convenient, but does mask how different class method mocking is. – Ben Flynn Jul 18 '13 at 16:16