スウィズリングは動的メソッド交換を行っていません。これは私が使用したコードです.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 は呼び出されず、実際のメソッドのみが呼び出されます。どちらのメソッドもクラス メソッドであることに注意してください。