How to mock class method (+)?

jianhua picture jianhua · Dec 8, 2011 · Viewed 7.3k times · Source

Need to write unit testing for the following code, I want to do mock for class method canMakePayments, return yes or no, so far no good method found dues to canMakePayments is a class method (+), seems all OCMock methods are all used for instance method (-).

You guys any suggestion or discussion will be appreciated. Thanks.

// SKPaymentQueue.h
// StoreKit
if ([SKPaymentQueue canMakePayments]){
   ....
}
else{
   ...
}

Answer

Christopher Pickslay picture Christopher Pickslay · Dec 8, 2011

One approach is to wrap the class method in your own instance method:

-(BOOL)canMakePayments {
    return [SKPaymentQueue canMakePayments];
}

Then you mock that method:

-(void)testCanHandlePaymentsDisabled {
    Foo *foo = [[Foo alloc] init];
    id mockFoo = [OCMockObject partialMockForObject:foo];
    BOOL paymentsEnabled = NO;
    [[[mockFoo stub] andReturnValue:OCMOCK_VALUE(paymentsEnabled)] canMakePayments];

    // set up expectations for payments disabled case
    ...

    [foo attemptPurchase];
}