---
title: 'Launch Arguments and Environment: Control App State'
description: A UI test cannot reach into the app to set things up (chapter 0 explained
  why). What it can do is decide how the app process starts. `XCUIApplication` has…
source_url:
  html: https://testingbot.com/resources/courses/xcuitest/launch-arguments-and-environment
  md: https://testingbot.com/resources/courses/xcuitest/launch-arguments-and-environment.md
---

Course

[XCUITest Tutorial: iOS UI Testing in Swift](https://testingbot.com/resources/courses/xcuitest)

Chapter 7 of 11

1. [1 XCUITest Tutorial: iOS UI Test Automation in Swift](https://testingbot.com/resources/courses/xcuitest)
2. [2 Add a UI Test Target and Run Your First Test](https://testingbot.com/resources/courses/xcuitest/add-a-ui-test-target)
3. [3 Element Queries and Accessibility Identifiers](https://testingbot.com/resources/courses/xcuitest/queries-and-accessibility-identifiers)
4. [4 Interactions and Assertions](https://testingbot.com/resources/courses/xcuitest/interactions-and-assertions)
5. [5 Waiting Without sleep(): waitForExistence and Predicates](https://testingbot.com/resources/courses/xcuitest/waiting-without-sleep)
6. [6 Screen Objects in Swift](https://testingbot.com/resources/courses/xcuitest/screen-objects)
7. [7 Launch Arguments and Environment: Control App State](https://testingbot.com/resources/courses/xcuitest/launch-arguments-and-environment)
8. [8 Build for Testing: The App and the Test Runner](https://testingbot.com/resources/courses/xcuitest/build-for-testing)
9. [9 Run XCUITest on Real iPhones with TestingBot](https://testingbot.com/resources/courses/xcuitest/run-on-testingbot)
10. [10 XCUITest in CI with GitHub Actions](https://testingbot.com/resources/courses/xcuitest/ci-github-actions)
11. [11 XCUITest Knowledge Check](https://testingbot.com/resources/courses/xcuitest/knowledge-check)

[Exit course](https://testingbot.com/resources/courses)

 Chapter 7 of 11 Intermediate 6 min read 2 quick checks Updated Nov 2026 

# Launch Arguments and Environment: Control App State
On this page
1. [The app side](https://testingbot.com#the-app-side)
2. [A base class for the tests](https://testingbot.com#a-base-class-for-the-tests)
3. [Why not just mock everything?](https://testingbot.com#why-not-just-mock-everything)

A UI test cannot reach into the app to set things up (chapter 0 explained why). What it can do is decide how the app process starts. `XCUIApplication` has two properties for that, and they are the main tool for fast, independent UI tests:

- **`launchArguments`** : an array of strings, the process's command-line arguments.
- **`launchEnvironment`** : a dictionary of environment variables.

Both are applied at the next `launch()`. The app reads them from `ProcessInfo` at start-up and puts itself into the state the test asks for.

## The app side[#](https://testingbot.com#the-app-side)

The Tasks app understands four switches. The store reads three of them when it is created:

```swift
init() {
    let info = ProcessInfo.processInfo
    if info.arguments.contains("-resetState") {
        UserDefaults.standard.removeObject(forKey: key)
    }
    if let data = UserDefaults.standard.data(forKey: key),
       let saved = try? JSONDecoder().decode([TaskItem].self, from: data) {
        tasks = saved
    }
    if let seed = info.environment["UITEST_SEED_TASKS"] {
        tasks = seed.split(separator: ",").map { TaskItem(title: String($0)) }
    }
    signedIn = info.environment["UITEST_SKIP_LOGIN"] == "1"
    loginDelay = Double(info.environment["UITEST_LOGIN_DELAY"] ?? "") ?? 2.0
}
```

and the app entry point handles the fourth:

```swift
init() {
    let args = ProcessInfo.processInfo.arguments
    if args.contains("-disableAnimations") {
        UIView.setAnimationsEnabled(false)
    }
}
```

| Switch | Effect |
| --- | --- |
| `-resetState` (argument) | Deletes stored tasks, so every test starts empty |
| `UITEST_SKIP_LOGIN=1` | Starts signed in, on the task list |
| `UITEST_SEED_TASKS=a,b,c` | Starts with these tasks |
| `UITEST_LOGIN_DELAY=0.2` | Makes the pretend sign-in call faster |
| `-disableAnimations` (argument) | Turns off UIKit animations |

A convention that helps: **arguments for flags, environment for values**. And keep the names obviously test-only (`UITEST_...`) so nobody mistakes them for product configuration.

In a production app, wrap these hooks in `#if DEBUG` (or a dedicated test build configuration) so they are not compiled into the App Store build. Note that the build you send to a device cloud in chapters 7 and 8 must then be a configuration that includes them; the course builds Debug for exactly that reason.

Arguments of the form `-SomeKey value` have a second use you get for free: Foundation puts them into the `UserDefaults` argument domain, overriding stored defaults for that run. Passing `["-AppleLanguages", "(de)"]` is the usual way to start an app in German for a localisation test, without touching the device settings.

## A base class for the tests[#](https://testingbot.com#a-base-class-for-the-tests)

With the switches in place, a small base class gives every test one call that sets up a known state:

```swift
import XCTest

class TasksUITestCase: XCTestCase {
    let app = XCUIApplication()

    override func setUpWithError() throws {
        continueAfterFailure = false
    }

    /// Starts the app in a known state: empty store, no animations,
    /// optionally signed in and with seeded tasks.
    @discardableResult
    func launch(signedIn: Bool = true, tasks: [String] = []) -> TaskListScreen {
        app.launchArguments = ["-resetState", "-disableAnimations"]
        app.launchEnvironment["UITEST_SKIP_LOGIN"] = signedIn ? "1" : "0"
        if !tasks.isEmpty {
            app.launchEnvironment["UITEST_SEED_TASKS"] = tasks.joined(separator: ",")
        }
        app.launch()
        return TaskListScreen(app: app)
    }
}
```

It returns the screen object from chapter 5, so tests start where they need to be:

```swift
import XCTest

final class AppStateTests: TasksUITestCase {

    func testCompletingTheLastOpenTask() throws {
        let list = launch(tasks: ["Buy milk", "Call Anna"])
            .waitUntilShown()

        list.toggle("Buy milk").toggle("Call Anna")

        XCTAssertEqual(list.openCount, "0 open")
    }

    func testTasksSurviveARelaunch() throws {
        launch().waitUntilShown().add("Pay rent")

        // Relaunch without -resetState: the stored task must still be there.
        app.terminate()
        app.launchArguments = ["-disableAnimations"]
        app.launchEnvironment = ["UITEST_SKIP_LOGIN": "1"]
        app.launch()

        XCTAssertTrue(TaskListScreen(app: app).row("Pay rent").waitForExistence(timeout: 5))
    }

    func testFastLoginForTheSignInFlow() throws {
        app.launchEnvironment["UITEST_LOGIN_DELAY"] = "0.2"
        launch(signedIn: false)

        LoginScreen(app: app)
            .signIn(email: "anna@example.com", password: "secret")
    }
}
```

All three passed on the simulator and on the real iPhones in chapter 8. What each one shows:

- **`testCompletingTheLastOpenTask`** needs two tasks to exist. Seeding them takes no time; adding them through the UI would take several seconds and would fail this test whenever adding is broken, which another test already covers. Test one thing per test, and set up everything else through the side door.
- **`testTasksSurviveARelaunch`** tests persistence, so it deliberately launches a second time _without_ `-resetState`. `terminate()` followed by `launch()` is how you test anything that should survive an app restart.
- **`testFastLoginForTheSignInFlow`** still goes through the real sign-in screen, but with a shorter fake delay. The value is set before `launch(...)`, which only adds keys to `launchEnvironment` and so keeps it.

Tests pass one at a time but fail when the whole suite runs: a test expecting an empty list finds tasks from an earlier test. What is the fix?

 Run the tests in alphabetical order Delete the tasks through the UI at the end of every test Launch every test with a reset switch (like `-resetState`) that the app handles at start-up Reinstall the simulator between tests

The app's stored data outlives the process, so each test must start from a known state. Clean-up at the end does not run when a test fails halfway, ordering hides the dependency instead of removing it, and reinstalling per test is very slow.

## Why not just mock everything?[#](https://testingbot.com#why-not-just-mock-everything)

Launch switches make tests fast and focused, but each one is a code path that real users never take. Keep at least one test per critical journey that goes through the real screens (here, `testSignInWaitsForTheTaskList` and the screen object test), and use switches to skip the parts a test is _not_ about. If the app talks to a backend, the same mechanism can point it at a stub server or a staging environment (`API_BASE_URL=...`), which is usually better than mocking network calls inside the app.

The app reads `UITEST_SKIP_LOGIN` in a `#if DEBUG` block. The UI tests pass locally but on a device cloud every test that expects the task list sees the sign-in screen. What is the likely cause?

 The uploaded app was built with the Release configuration, so the hook was compiled out Device clouds strip environment variables from apps `launchEnvironment` only works on simulators

The runner passes launch arguments and environment on simulators and real devices alike; in chapter 8 these tests pass on real iPhones. A hook inside `#if DEBUG` simply does not exist in a Release build, so build the configuration that contains it.

Next: building the app and the tests so they can run somewhere other than your Mac's simulator.

[Previous · Chapter 6 Screen Objects in Swift](https://testingbot.com/resources/courses/xcuitest/screen-objects) [Next · Chapter 8 Build for Testing: The App and the Test Runner](https://testingbot.com/resources/courses/xcuitest/build-for-testing)

On this page

1. [The app side](https://testingbot.com#the-app-side)
2. [A base class for the tests](https://testingbot.com#a-base-class-for-the-tests)
3. [Why not just mock everything?](https://testingbot.com#why-not-just-mock-everything)

Certification

Earn the free, resume-worthy TestingBot XCUITest Certification for this course.

[How it works](https://testingbot.com/resources/courses/xcuitest/certification)
