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

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

    Elvind's answer isn't bad if you want to have what used to be called pure "Logic Tests". If you'd still like to run your containing host application yet conditionally execute or not execute code depending on whether tests are run, you can use the following to detect if a test bundle has been injected:

    if NSProcessInfo.processInfo().environment["XCTestConfigurationFilePath"] != nil {
         // Code only executes when tests are running
    }
    

    I used a conditional compilation flag as described in this answer so that the runtime cost is only incurred in debug builds:

    #if DEBUG
        if NSProcessInfo.processInfo().environment["XCTestConfigurationFilePath"] != nil {
            // Code only executes when tests are running
        }
    #endif
    

    Edit Swift 3.0

    if ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil {
        // Code only executes when tests are running
    }
    
    0 讨论(0)
  • 2021-01-30 05:19

    First add variable for testing:

    and use that in your code:

     if ProcessInfo.processInfo.environment["IS_UNIT_TESTING"] == "1" {
                     // Code only executes when tests are running
     } 
    
    0 讨论(0)
  • 2021-01-30 05:19

    Apparently in Xcode12 we need to search in the environment key XCTestBundlePath instead of XCTestConfigurationFilePath if you are using the new XCTestPlan

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

    I use this in application:didFinishLaunchingWithOptions:

    // Return if this is a unit test
    if let _ = NSClassFromString("XCTest") {
        return true
    }
    
    0 讨论(0)
  • 2021-01-30 05:26

    Worked for me:

    Objective-C

    [[NSProcessInfo processInfo].environment[@"DYLD_INSERT_LIBRARIES"] containsString:@"libXCTTargetBootstrapInject"]

    Swift: ProcessInfo.processInfo.environment["DYLD_INSERT_LIBRARIES"]?.contains("libXCTTargetBootstrapInject") ?? false

    0 讨论(0)
  • 2021-01-30 05:27
    var isRunningTests: Bool {
        return ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil
    }
    

    Usage

    if isRunningTests {
        return "lena.bmp"
    }
    return "facebook_profile_photo.bmp"
    
    0 讨论(0)
提交回复
热议问题