Exit course
Chapter 7 of 11 Intermediate 6 min read 2 quick checks Updated

Launch Arguments and Environment: Control App State

On this page
  1. The app side
  2. A base class for the tests
  3. 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#

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

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:

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#

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

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:

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?

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?#

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 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.