Mocking a method in OCMock for all instances of a class
objective-c, ocmock, unit-testing
Solution
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;
}
Problem
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]; ```