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

后端 未结 15 683
借酒劲吻你
借酒劲吻你 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: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.

提交回复
热议问题