我目前正在尝试测试一些使用的代码,AVAudioSession
并且我尝试模拟它,因为它是一个单例,到目前为止证明很困难,我做了一些研究,并想到了调整它获取实例的方式然后实际初始化的想法你想要的子类,但我无法弄清楚要调配的方法。我尝试了 sharedInstance 并且class_addMethod()
返回 yes 说它是添加而不是替换它。我可以以这种方式有效地模拟单身人士吗?
@interface AVAudioSessionFake : AVAudioSession
@property (readonly, nonatomic) BOOL wasSetActiveErrorCalled;
-(instancetype)initStub;
@end
@implementation AVAudioSessionFake
+ (void)load
{
[AVAudioSessionFake swizzleOriginalMethod:@"sharedInstance" with:@"initStub"];
}
+ (void)swizzleOriginalMethod:(NSString*)Original with:(NSString*)replacement
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^
{
Class class = [self class];
SEL originalSelector = NSSelectorFromString(Original);
SEL swizzledSelector = NSSelectorFromString(replacement);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
BOOL didAddMethod =
class_addMethod(class,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if (didAddMethod)
{
class_replaceMethod(class,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
}
else
{
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}
-(instancetype)initStub
{
return [[[self class]alloc]init];
}
- (BOOL)setActive:(BOOL)active error:(NSError *__autoreleasing *)outError
{
_wasSetActiveErrorCalled = YES;
return [super setActive:active error:outError];
}
@end