In XCUITest, how do launchArguments and launchEnvironment put the app into a known state, and why can't the test set that state directly?
answer
- two processes, not one
- the test sees accessibility data only
- passed when the app starts
- changes apply at the next launch
- launch() kills a running instance first
basics
~20 sThe UI test runs in its own process and sees only what accessibility exposes, so it can't touch the app's objects. It sets XCUIApplication's launchArguments and launchEnvironment before launch(), and the app reads them at startup to choose stubs and test data.
solid answer
~40 sA UI test drives the app from a separate test-runner process. It sees the element tree that accessibility exposes, never the app's view models or singletons. To control state, the test sets `launchArguments` (an array of strings) and `launchEnvironment` (a string dictionary) on `XCUIApplication`, then calls `launch()`. The app reads them through `ProcessInfo.processInfo.arguments` and `environment` and, for example, points its API client at a local stub and signs in a test user. Changes made after launch apply only at the next launch. `launch()` terminates an already running instance for a clean start. `activate()` keeps a running instance, and if it has to launch the app it reuses the arguments from the last `launch()`.
code
swift · 15 linesimport XCTest
final class CheckoutUITests: XCTestCase {
@MainActor
func testPaysForTwoHoursAgainstStub() {
let app = XCUIApplication()
app.launchArguments += ["-uiTesting", "-signedInDriver"]
app.launchEnvironment["API_BASE_URL"] = "http://localhost:8080"
app.launch() // terminates any running instance first
app.buttons["durationTwoHours"].tap()
app.buttons["payButton"].tap()
XCTAssertTrue(app.staticTexts["receiptTotal"].waitForExistence(timeout: 10))
}
}go deeper
Recall that launchArguments and launchEnvironment are set on XCUIApplication before launch(), and that the app reads them with ProcessInfo.
Explain the two-process model: the test sees accessibility attributes only, which is why state crosses at launch rather than by poking objects.
Show the lifecycle rules: launch() terminates a running instance, activate() does not, and argument changes apply at the next launch.
Weigh a small test-only launch branch in the app against slower setup through the UI, and how you keep that branch out of shipping builds.
## Two processes, one screen A UI test does not run inside your app. Xcode builds the app and a separate **test runner**. The runner executes your `XCTestCase` methods and drives the app as another process. `XCUIApplication` is only a *proxy*: `launch()` starts the real app, and `terminate()` stops it, through the debugger when one is attached and with a `SIGKILL` otherwise. So the test can only see what the app exposes to the accessibility system. `XCUIElementAttributes` lists it: `identifier`, `label`, `value`, `title`, `frame`, `elementType`, `isEnabled`, `isSelected`, `placeholderValue`, size classes and `hasFocus`. There is no handle on a view model, a database or a singleton. A unit test hosted in the app can call straight into it, with `@testable import` for internal types; a UI test cannot, because its code never runs inside the app. That is why state has to be set up *before* the app starts, or by driving the UI. ## The launch configuration `XCUIApplication` has two mutable properties: | Property | Type | Read in the app with | |---|---|---| | `launchArguments` | `[String]` | `ProcessInfo.processInfo.arguments` | | `launchEnvironment` | `[String: String]` | `ProcessInfo.processInfo.environment` | If you don't change them, they hold what Xcode would pass on launch anyway. You can add, change or remove entries. Apple's documentation adds one rule that catches people: you may change them after launch, but **the change does not affect the running session**. It applies the next time the app launches. For a parking-payment suite, a typical setup is: - an argument such as `-uiTesting`, which tells the app to use fake services and start from empty storage; - an argument such as `-signedInDriver`, which seeds a known account so the test skips the sign-in screens; - an environment variable such as `API_BASE_URL`, which points the network layer at a stub server the suite controls. These names are the app's own convention. XCUITest just passes the strings, and the app decides what they mean. Keep that branch small and out of release builds (for example behind a compile-time flag) so a test-only path cannot ship by accident. ## Launch, activate, terminate The three lifecycle calls behave differently, and interviewers like the difference: 1. **`launch()`** is synchronous. When it returns, the app is ready to handle events. If an instance is already running, it is **terminated first** so the new launch starts clean. A launch failure fails the test and stops it. 2. **`activate()`** brings the app to the foreground **without** terminating a running instance. If the app is not running it is launched, and if it was earlier launched with `launch()`, the same arguments and environment are supplied again. 3. **`terminate()`** stops the running instance. After it returns successfully, `state` is `.notRunning`. `state` is updated by passive monitoring, so it changes asynchronously. To wait for a transition, use `wait(for:timeout:)` with an `XCUIApplication.State`, such as `.runningForeground`, and assert its `Bool` result. `init(bundleIdentifier:)` creates a proxy for a different app, such as Settings, when a flow leaves your own app. ## Why this beats driving the UI to set up You could sign in through the UI at the start of every test, but each test then depends on the sign-in screens and the network. Launch arguments give each test a known starting point that a few lines can describe. Three habits keep it reliable: - Set arguments and environment **before** `launch()`, in each test or in setup, since a later change waits for the next launch. - Call `launch()` once per test so each test starts from a fresh process, not from the previous test's leftovers. - Point at a stub you control. A shared staging server gives the run the same timing and data drift you were trying to remove. ## Where UI tests live Apple's UI-recording guide starts every UI test as a method on an `XCTestCase` subclass, with a name that begins with `test`. That is why a codebase that writes its new unit tests with Swift Testing still keeps its UI tests in XCTest classes, and why the launch configuration above is set inside an `XCTestCase` method. ## Where the line sits How a stub server is built, or which journeys deserve an end-to-end run at all, are questions for test design. This question is about what XCUITest gives you: two properties that cross the process boundary at launch, and lifecycle calls with exact rules about when they take effect.
- A test sets a launch argument in the middle of the test, then calls activate(). Does the running app see it?No. Changes to `launchArguments` after a launch apply only at the next launch, and `activate()` does not relaunch an app that is already running. To apply the new argument, call `launch()`, which terminates the running instance and starts it again with the current arguments and environment.
- How would a UI test confirm that the app really went to the background after pressing the Home button?Press the button with `XCUIDevice.shared.press(.home)`, then wait with `app.wait(for:timeout:)` for the background state your step needs, `.runningBackground` or `.runningBackgroundSuspended`, and assert the Bool. `state` is updated asynchronously by monitoring, so reading it right away can return the old value; the wait returns as soon as the state is reached.
- Thinking a UI test can reach the app's view model with @testable import
- Changing launchArguments after launch and expecting the running app to see it
- Believing activate() always restarts the app with fresh arguments
- Signing in through the UI at the start of every single test
- Leaving the test-only launch branch active in release builds