How to mock a class method (+)?

We need to write unit testing for the following code, I want to make a mock for the canMakePayments class method, return yes or no, so far no good method has found contributions for canMakePayments - the class method (+), it seems that all OCMock methods are all used, for example , by (-) method.

You guys, any suggestion or discussion will be appreciated. Thank you

// SKPaymentQueue.h // StoreKit if ([SKPaymentQueue canMakePayments]){ .... } else{ ... } 
+4
source share
2 answers

Since you cannot intercept a method by providing another instance, what you can do for a class method is to provide another class. Something like that:

 + (Class)paymentQueueClass { return [SKPaymentQueue class]; } 

Then the dial peer becomes:

 Class paymentQueueClass = [[self class] paymentQueueClass]; if ([paymentQueueClass canMakePayments]) ... 

A “test seam” or control point is entered here to specify a class other than SKPaymentQueue . Now make a replacement:

 static BOOL fakeCanMakePayments; @interface FakePaymentQueue : SKPaymentQueue @end @implementation FakePaymentQueue + (void)setFakeCanMakePayments:(BOOL)fakeValue { fakeCanMakePayments = fakeValue; } + (BOOL)canMakePayments { return fakeCanMakePayments; } @end 

Strictly speaking, this is not an “object layout” - it is a “fake object”. The difference is that the layout of the object checks how it is called. A fake object simply provides sealed results.

Now create a subclass for testing the source class we want to test.

 @interface TestingSubclass : OriginalClass @end @implementation TestingSubclass + (Class)paymentQueueClass { return [FakePaymentQueue class]; } @end 

So, you see, this replaces SKPaymentQueue with FakePaymentQueue . Now your tests can work against TestingSubclass .

+4
source

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

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

Then you mock this 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]; } 
+12
source

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


All Articles