强制删除使用dispatch_once创建的测试代码中的单例 [英] Force deletion of singleton in test code that was created with dispatch_once
本文介绍了强制删除使用dispatch_once创建的测试代码中的单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在为模型类编写一些单元测试代码,并希望在应用程序退出和重新启动期间模拟该类的行为.我可以通过删除并重新分配对象来实现此目的,但是它是单例对象,因此以下代码没有达到预期的效果:
I'm writing some unit test code for a model class and want to simulate the behavior of the class during app exit and relaunch. I could achieve this by deleting and re-allocing the object, however its a singleton and thus the following code doesn't have the desired effect:
+ (id) sharedInstance
{
static MyModel *singleton = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^ {
singleton = [[MyModel alloc] initSharedInstance];
});
return singleton;
}
// Test code:
MyModel* gModel = [MyModel sharedInstance];
... tests
gModel = nil;
gModel = [MyModel sharedInstance];
... more tests
是否有一个整洁的解决方案,以便我可以删除/重新创建对象?
Is there a neat solution so I can delete/recreate the object?
推荐答案
static MyModel *singleton = nil;
static dispatch_once_t onceToken;
+ (instancetype) sharedInstance
{
dispatch_once(&onceToken, ^ {
if (singleton==nil){
singleton = [[MyModel alloc] initSharedInstance];
}
});
return singleton;
}
+(void)setSharedInstance:(MyModel *)instance {
onceToken = 0;
singleton = instance;
}
没有:
[MyModel setSharedInstance:nil];
请注意,您也可以将其设置为任意类以对其进行模拟.
Note that you can also set it to an arbitrary class to mock it.
[MyModel setSharedInstance:someMock];
这篇关于强制删除使用dispatch_once创建的测试代码中的单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文