Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking a method in OCMock for all instances of a class

I want to mock an instance method for all instances of a class using OCMock however I don't have the instance of the class to override it rather it is created inside the method that I'm testing.

So my question is: is it possible to override this method for all instances of a class or will I need to inject that instance into the method rather than create it inside the method?

i.e.

[[ClassThatHasTheInstanceMethodToOverride andCall:@selector(callThisMethodInstead) onObject:self] someInstanceMethod];
like image 760
wibosco Avatar asked May 03 '12 13:05

wibosco


Video Answer


1 Answers

I got there in the end with this set of methods:

Method originalMethod = nil; Method swizzleMethod = nil;

#import <objc/runtime.h>

....

- (void) swizzleInstanceMethodForInstancesOfClass:(Class)targetClass selector:(SEL)selector
{
    originalMethod = class_getInstanceMethod(targetClass, selector);
    swizzleMethod = class_getInstanceMethod([self class], selector);
    method_exchangeImplementations(originalMethod, swizzleMethod);
}

- (void) deswizzle
{
    method_exchangeImplementations(swizzleMethod, originalMethod);
    swizzleMethod = nil;
    originalMethod = nil;
}
like image 177
wibosco Avatar answered Oct 19 '22 23:10

wibosco