Xcode test coverage falsely indicates methods covered by testing

If you have a normal Xcode project that you added unit testing to, you may find that the testing code coverage inside of Xcode shows that there is a lot more code being tested than actually is. Or if you have an app that does complex and/or lengthy things in its initialization, you may get tired of waiting for all that stuff to run just because you want to run the tests to see if they pass.

Luckily, I figured out a way to short circuit the app from its normal initialization if you are invoking it for the purposes of testing. Here is the code you would need to put in your app delegate’s didFinishLaunchingWithOptions method, preferably right at the top:

#if defined(DEBUG_VERSION)
    if ([[[NSProcessInfo processInfo] arguments] containsObject:@"-FNTesting"])
        DebugLog(@"The -FNTesting argument is in use, so the app will just create a blank view controller");
        UIViewController *vc = [[UIViewController alloc] init];
        navigationController = [[MyNavigationController alloc] initWithRootViewController:vc];
        [window setRootViewController:navigationController];
        return YES;

(The #if above uses a compiler variable that is only used in the debug scheme of the application. It’s a good plan all around to do this in your own code.)

Basically, this code only is going to run if your are doing a unit test run, and it just creates a blank view controller and returns.

BTW, Happy Pi Day. I meant to do this posting at 1:59 today to continue the pi theme, but got busy with work and forgot.

Leave a Reply