Last Updated: February 25, 2016
·
985
· dancali

How To Tell XCode Not To Run Your Main Target When Executing Your Tests

When you run the test target your iOS app in XCode, your app gets executed as well by default because the test target depends on the main target.

The problem with that is that there are times when you may not want to execute your app when running tests but you still want to keep the dependency. One such scenario might be when you stub out network requests globally in your unit tests and your main app fails.

I ran into this scenario once

Here's a simple trick to tell XCode not to run your main target when running your tests. All you have to do is add a simple if-statement in your main.m:


#import "AppDelegate.h"

int main(int argc, char * argv[])
{
    @autoreleasepool
    {
        if (NSClassFromString(@"XCTestCase") != nil)
        {
            // Tell XCode to run this only when in test-mode
            return UIApplicationMain(argc, argv, nil, @"MyAppTests");
        }

        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}