How to access launchEnvironment and launchArguments set in XCUIApplication, running UI tests in XCode? How to access launchEnvironment and launchArguments set in XCUIApplication, running UI tests in XCode? xcode xcode

How to access launchEnvironment and launchArguments set in XCUIApplication, running UI tests in XCode?


If you set launchArguments in a UI Test (Swift):

let app = XCUIApplication()app.launchArguments.append("SNAPSHOT")app.launch()

Then read them in your App using:

swift 2.x:

if NSProcessInfo.processInfo().arguments.contains("SNAPSHOT") {   // Do snapshot setup}

Swift 3.0

if ProcessInfo.processInfo.arguments.contains("SNAPSHOT") {}

To set environment variables, use launchEnvironment and NSProcessInfo.processInfo().environment, respectively, instead.


Building on Joey C.'s answer, I wrote a small extension to avoid using raw strings in the app. This way you avoid any typo issue and get autocompletion.

extension NSProcessInfo {    /**     Used to recognized that UITestings are running and modify the app behavior accordingly     Set with: XCUIApplication().launchArguments = [ "isUITesting" ]     */    var isUITesting: Bool {        return arguments.contains("isUITesting")    }    /**     Used to recognized that UITestings are taking snapshots and modify the app behavior accordingly     Set with: XCUIApplication().launchArguments = [ "isTakingSnapshots" ]     */    var isTakingSnapshots: Bool {        return arguments.contains("isTakingSnapshots")    }}

This way you can use

if NSProcessInfo.processInfo().isUITesting {   // UITesting specific behavior,   // like setting up CoreData with in memory store}

Going further, the various arguments should probably go into an enum that could be reused in the UITest when setting the launchArguments.


It's also interesting to note that arguments passed to XCUIApplication.launchArguments are also available from UserDefaults.

In your XCTestCase

let app = XCUIApplication()app.launchArguments.append("-ToggleFeatureOne")app.launchArguments.append("true")app.launch()

In your target under test

UserDefaults.standard.bool(forKey: "ToggleFeatureOne") // returns true

From here you could create extensions on UserDefaults to provide handy run time toggles.

This is the same mechanism the Xcode schemes "arguments passed on launch" uses. Launch arguments and their effect on UserDefaults are documented under Preferences and Settings Programming Guide.