Search code examples
iosunit-testinguiviewcontrollertddocunit

Prevent app from creating a viewcontroller when running unit tests


When I test my app using OCUnit, it sets up the AppDelegate, window and rootViewController as usual before running the tests. My rootViewController then adds itself as an observer for some NSNotifications.

When I test these notifications with isolated test instances and mock observers, the notification handler of the automatically created rootViewController is called as well, which causes some of my tests to fail.

Is there a way to keep OCUnit from creating the rootViewController or make it use a different ViewController class when running in test mode? It would be cool if this could be done without writing special test-related code in my app code.


Solution

  • Update: What I do today is slightly different from the answer below. See How to Easily Switch Your App Delegate for Testing

    It does require adding a little bit of test-specific code to your app code. Here's what I do to avoid my full startup sequence:

    Edit the scheme

    • Select the Test action
    • In "Test" select the Arguments tab
    • Disable "Use the Run action's options"
    • Add an environment variable, setting runningTests to YES

    Edit your app delegate

    • Add the following to -application:didFinishLaunchingWithOptions: as soon as it makes sense to:

      #if DEBUG
          if (getenv("runningTests"))
              return YES;
      #endif
      
    • Do the same for -applicationDidBecomeActive: but simply return.