iOS测试:dispatch_once被调用两次.在应用程序中排名第一,在测试中排名第二.观察者问题 [英] iOS Testing: dispatch_once get called twice. First in App, second in Test. Problems with Observers

查看:189
本文介绍了iOS测试:dispatch_once被调用两次.在应用程序中排名第一,在测试中排名第二.观察者问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个singelton类,它将在应用程序委托中创建.

I have a singelton class which will be create in the app delegate.

当我运行XCTTests时,将再次创建它.

When i run XCTTests then its get create a second time.

+ (instancetype)urlSchemeManager
{
    static dispatch_once_t onceToken;
    static UrlSchemeManager* _sharedInstance;

    dispatch_once(&onceToken, ^{

        _sharedInstance = [UrlSchemeManager new];


    });
    return _sharedInstance;
}

这导致两个不同的实例.如果我只是将其用于单元测试,这是没有问题的. 但是在集成测试中,当我为urlSchmemeManager注册观察者时,我得到了EXC_BAD_ACCESS,因为rootViewController已经在用户界面中对其进行了观察.

This is resulting in two different instances. This was no problem if i just use it for unit test. But in the integration test, when i register an observer for urlSchmemeManager i get a EXC_BAD_ACCESS, because it was already observed by the rootViewController (in the UI).

在RootViewController中:

In RootViewController:

UrlSchemeManager * schemeManager = [GlobalSpace globalSpace].urlSchemeManager;
[schemeManager addObserver:self forKeyPath:OBSERVER_KEY_URL_SCHEME_MANAGER_CONTENT_MORE options:NSKeyValueObservingOptionNew context:nil];

有人知道我如何解决这个问题吗?

Does anyone has an idea how i can get around this problem?

推荐答案

我在运行测试套件时多次调用dispatch_once时遇到了同样的问题.我通过从测试的目标成员资格中删除单例类来解决此问题.

I had the same problem with dispatch_once being called multiple times when running a test suite. I fixed it by removing the singleton class from the Target Membership of the Test.

完成此操作后,请确保您的测试目标依赖于构建阶段"中的应用程序,以使测试仍然了解该类.

Once you've done that make sure that your test target is dependent on your application in "Build Phases" so that the test still knows about the class.

此后,应该运行测试,并且单例只能实例化一次.

After that, the test should run and the singleton should only be instantiated one time.

这篇关于iOS测试:dispatch_once被调用两次.在应用程序中排名第一,在测试中排名第二.观察者问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆