Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Detect if a Swift iOS app delegate is running unit tests
import UIKit
// Detect if the app is running unit tests.
// Note this only detects unit tests, not UI tests.
func isRunningUnitTests() -> Bool {
let env = NSProcessInfo.processInfo().environment
if let injectBundle = env["XCInjectBundle"] {
return NSString(string: injectBundle).pathExtension == "xctest"
}
return false
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if(isRunningUnitTests()) {
print("TESTING")
// Create an empty window. Useful for unit tests that might need to alter the view heirarchy or
// add views during their tests.
let window = UIWindow(frame: UIScreen.mainScreen().bounds)
window.rootViewController = UIViewController()
window.makeKeyAndVisible()
self.window = window
return true
}
// Perform the normal app init here
makeWindow()
return true
}
func makeWindow() {
// Do whatever you need here to create the root view controller of the app.
let vc = UIStoryboard.init(name: "Main", bundle: NSBundle.mainBundle()).instantiateViewControllerWithIdentifier("ViewController")
let window = UIWindow(frame: UIScreen.mainScreen().bounds)
window.rootViewController = vc
window.makeKeyAndVisible()
self.window = window
}
}
@haarismuneer

This comment has been minimized.

Copy link

haarismuneer commented Jul 26, 2016

Thank you so much! This is the only solution that ended up working for me.

@kdawgwilk

This comment has been minimized.

Copy link

kdawgwilk commented Oct 11, 2017

This appears to have broke in Xcode 9 :(

@PeqNP

This comment has been minimized.

Copy link

PeqNP commented Nov 4, 2017

It looks like they changed it to XCInjectBundleInto. I've been using the following with pretty good success between versions:

func isRunningUnitTests() -> Bool {
    let env = ProcessInfo.processInfo.environment
    if env["XCTestConfigurationFilePath"] != nil {
        return true
    }
    return false
}
@igordeoliveirasa

This comment has been minimized.

Copy link

igordeoliveirasa commented Mar 26, 2018

Isn't it better?

func isRunningUnitTests() -> Bool {
    return ProcessInfo.processInfo.environment.keys.contains("XCTestConfigurationFilePath")
}
@nhnam

This comment has been minimized.

Copy link

nhnam commented Jul 18, 2018

It works for me !
screen shot 2018-07-18 at 12 23 29 pm
screen shot 2018-07-18 at 12 23 37 pm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.