Search code examples
iostestinggrand-central-dispatchobserversxctest

iOS Testing: dispatch_once get called twice. First in App, second in Test. Problems with Observers


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

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;
}

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).

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?


Solution

  • 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.