Swizzling 不执行动态方法交换。这是我使用的代码。我听说这是一个解决方案,其中依赖注入无法在 xcode 7 的 XCTest 中执行。你能举例说明 Swizzling over DI(Dependency) 吗?
#import "TNUserDetail+Swizzle.h"
#import <objc/runtime.h>
@implementation TNUserDetail (Swizzle)
+ (void) swizzleInstanceSelector:(SEL)originalSelector
withNewSelector:(SEL)newSelector
{
Method originalMethod = class_getClassMethod(self, originalSelector);
Method newMethod = class_getClassMethod(self, newSelector);
BOOL methodAdded = class_addMethod([self class],
originalSelector,
method_getImplementation(newMethod),
method_getTypeEncoding(newMethod));
if (methodAdded) {
class_replaceMethod([self class],
newSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, newMethod);
}
}
+(BOOL)isSignUpSwizzle {
return sighUp;
}
Test
_____
@implementation TNSettingsViewControllerTests
- (void)setUp {
[super setUp];
UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
self.settingVC = [sb instantiateViewControllerWithIdentifier:@"TNSettingsViewController"];
[self.settingVC performSelectorOnMainThread:@selector(loadView) withObject:nil waitUntilDone:YES];
[self.settingVC performSelectorOnMainThread:@selector(viewWillAppear:) withObject:nil waitUntilDone:YES];
}
-(void)testTwitterConnectSwitchValueChanged
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[TNUserDetail swizzleInstanceSelector:@selector(isSignUpWithTwitter) withNewSelector:@selector(isSignUpSwizzle)];
[TNUserDetail isSignUpWithTwitter];
});
sighUp = YES;
self.settingVC.twitterConnectSwitch.on = YES;
[self.settingVC.twitterConnectSwitch sendActionsForControlEvents:UIControlEventValueChanged];;
}
在这里,当我调用 [TNUserDetail isSignUpWithTwitter] 时,+(BOOL)isSignUpSwizzle 没有被调用,只有实际的方法被调用。出了什么问题。注意这两种方法都是类方法。