C & OC Mock's Goal - Bullying a Class?

I need to determine if a class method has been called or not. How can I do this using OCMock?

+4
source share
4 answers

Starting with OCMock 2.1, this is supported out of the box. Now you can stub class methods in the same way as stub instance methods.

+6
source

One approach is to wrap a class method in a method of your own class. So let your class call [SomeOtherClass classMethod:someString] . You can create an invokeClassMethod: method in your class as follows:

 -(NSString *)invokeClassMethod:(NSString *)someString { return [SomeOtherClass classMethod:someString]; } 

Then, in your test, you create a partial layout and expect invokeClassMethod:

 -(void)testSomething { id partialMock = [OCMockObject partialMockForObject:actual]; [[[partialMock expect] andReturn:@"foo"] invokeClassMethod:@"bar"]; [actual doSomething:@"bar"]; [partialMock verify]; } 

If you want to verify that invokeClassMethod not called, you can throw an exception:

 -(void)testSomethingElse { id partialMock = [OCMockObject partialMockForObject:actual]; [[[partialMock stub] andThrow:[NSException exceptionWithName:@"foo" reason:@"Should not have called invokeClassMethod:" userInfo:nil] invokeClassMethod:OCMOCK_ANY]; [actual doSomething:@"bar"]; } 

Resolving will cause the test to fail if invokeClassMethod is invokeClassMethod .

+3
source

As zneak said in his comment on your question, see this answer ,

And from the comments there, checkout this block implementation of the swizzling class method.

OCMock doesn't seem to support what you want to do, but this solution is pretty nice!

+2
source

Alternatively, suppose you have a class:

 @interface ABCCleverClass : NSObject + (id)specialMethod; @end 

and you want to mock this class method. One option is to create a category in this class that defines and implements test support. Then you can change the implementation of the class method in the tested class to your layout from the category.

 #import <objc/runtime.h> @interface ABCCleverClass (TestSupport) + (id)mockSpecialMethod; @end @implementation ABCCleverClass (TestSupport) + (void)load { Method original = class_getClassMethod([ABCCleverClass class], @selector(specialMethod)); Method mocked = class_getClassMethod([ABCCleverClass class], @selector(mockSpecialMethod)); method_exchangeImplementations(original, mocked); } + (id)mockSpecialMethod { // Perform mock method. You may need to add more class methods // in order to configure this. } @end 
+1
source

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


All Articles