7

我想使用 OCMock 模拟类的所有实例的实例方法,但是我没有类的实例来覆盖它,而是在我正在测试的方法中创建它。

所以我的问题是:是否可以为类的所有实例重写此方法,还是我需要将该实例注入方法而不是在方法中创建它?

IE

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

1 回答 1

3

我最终通过这组方法到达了那里:

方法 originalMethod = nil; 方法 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;
}
于 2012-05-03T14:07:24.253 回答