How to let the app know if it's running Unit tests in a pure Swift project?

后端 未结 15 680
借酒劲吻你
借酒劲吻你 2021-01-30 05:08

One annoying thing when running tests in Xcode 6.1 is that the entire app has to run and launch its storyboard and root view controller. In my app this runs some server calls th

相关标签:
15条回答
  • 2021-01-30 05:39

    Combined approach of @Jessy and @Michael McGuire

    (As accepted answer will not help you while developing a framework)

    So here is the code:

    #if DEBUG
            if (NSClassFromString(@"XCTest") == nil) {
                // Your code that shouldn't run under tests
            }
    #else
            // unconditional Release version
    #endif
    
    0 讨论(0)
  • 2021-01-30 05:45

    Some of these approaches don't work with UITests and if you're basically testing with the app code itself (rather than adding specific code into a UITest target).

    I ended up setting an environment variable in the test's setUp method:

    XCUIApplication *testApp = [[XCUIApplication alloc] init];
    
    // set launch environment variables
    NSDictionary *customEnv = [[NSMutableDictionary alloc] init];
    [customEnv setValue:@"YES" forKey:@"APPS_IS_RUNNING_TEST"];
    testApp.launchEnvironment = customEnv;
    [testApp launch];
    

    Note that this is safe for my testing since I don't currently use any other launchEnvironment values; if you do, you would of course want to copy any existing values first.

    Then in my app code, I look for this environment variable if/when I want to exclude some functionality during a test:

    BOOL testing = false;
    ...
    if (! testing) {
        NSDictionary *environment = [[NSProcessInfo processInfo] environment];
        NSString *isRunningTestsValue = environment[@"APPS_IS_RUNNING_TEST"];
        testing = [isRunningTestsValue isEqualToString:@"YES"];
    }
    

    Note - thanks for RishiG's comment that gave me this idea; I just expanded that to an example.

    0 讨论(0)
  • 2021-01-30 05:46

    You can pass runtime arguments into the app depending on the scheme here...

    enter image description here

    But I'd question whether or not it is actually needed.

    0 讨论(0)
提交回复
热议问题