2012-05-03 48 views
5

我想用一個OCMock來模擬一個類的所有實例的實例方法,但是我沒有類的實例來重寫它,而是在方法內部創建它我正在測試。在OCMock中嘲諷一個類的所有實例的方法

所以我的問題是:是否有可能重寫此方法的所有類的實例,或者我需要將該實例注入該方法而不是在該方法內創建它?

[[ClassThatHasTheInstanceMethodToOverride andCall:@selector(callThisMethodInstead) onObject:self] someInstanceMethod]; 

回答

1

我與本組方法結束了那裏:

方法originalMethod =零; 方法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; 
}