skip to content

XCUITest

XCUITest drives the app from a separate process through XCUIApplication, element queries, gestures and waits. Interviewers ask about flakiness and why locators lean on accessibility identifiers.

on this pageshow

explore

questions

6

In XCUITest, how do you find a button by its accessibility identifier, tap it, and type text into a search field?

level: juniorimportance: must knowfreq 80%

answer

  1. query from the XCUIApplication proxy
  2. type-named query, then a string subscript
  3. the subscript matches more than the identifier
  4. typeText needs keyboard focus first
  5. labels move with copy edits and localization

basics

~20 s

Query from the XCUIApplication proxy, such as app.buttons["payButton"], then call tap(). For typing, tap the field so it has keyboard focus, then call typeText(_:). Identifiers beat labels because they don't change when the visible text does.

solid answer

~40 s

A UI test starts from `XCUIApplication()`, launches it, and builds queries such as `app.buttons["payButton"]` or `app.searchFields["zoneSearchField"]`. `buttons` is shorthand for `descendants(matching: .button)`, and the string subscript matches any identifying property: `identifier`, `title`, `label`, `value` or `placeholderValue`. The app sets the identifier: `accessibilityIdentifier` on a UIKit view (nil by default) or the `accessibilityIdentifier(_:)` modifier in SwiftUI. `tap()` taps a hittable point and first tries to scroll an offscreen element into view. `typeText(_:)` raises an error unless the element or a descendant has keyboard focus, so tap the field first. I prefer identifiers because a label follows copy edits and localization, while an identifier only changes when a developer changes it.

code

swift · 17 lines
swift
import XCTest

final class ZoneSearchUITests: XCTestCase {
    @MainActor
    func testSearchesForParkingZone() {
        let app = XCUIApplication()
        app.launch()

        let search = app.searchFields["zoneSearchField"]
        XCTAssertTrue(search.waitForExistence(timeout: 5))
        search.tap()                 // give the field keyboard focus
        search.typeText("4021")

        app.cells["zoneRow-4021"].tap()
        XCTAssertTrue(app.buttons["startParkingButton"].waitForExistence(timeout: 5))
    }
}

go deeper

for a junior

Recall the chain: XCUIApplication, a type-named query, a string subscript, then tap() or typeText(_:). Say where the identifier is set in the app.

for a middle

Explain that the subscript matches identifier, title, label, value or placeholderValue, and that typing raises an error without keyboard focus.

for a senior

Show the naming rule you would enforce for identifiers, unique per row and named for the role, so tests survive localization and redesigns.

for a principal

Weigh the cost of identifiers as part of the app's code review against brittle label queries that break each time copy or language changes.

## The pieces of a first UI test An XCUITest test drives your app the way a person would, from outside it. The test is a method on an `XCTestCase` subclass in a UI test target, and it talks to the app through a few types from Apple's UI-automation framework: - **`XCUIApplication`** is a *proxy* for the app. `XCUIApplication()` refers to the app set as the UI test target's *Target Application*, and `launch()` starts it. - **`XCUIElementQuery`** describes how to find elements, for example "all buttons in the app". - **`XCUIElement`** is one element that a query resolves to. You tap it, type into it and read its attributes. Nothing is looked up when you build a query. An element is resolved when you use it: when you call an event method like `tap()`, or read a property like `exists`. ## Building the query `XCUIApplication` is itself an element, so it has the **type-named query properties**: `buttons`, `searchFields`, `textFields`, `cells`, `staticTexts` and dozens more. Each one is shorthand for `descendants(matching:)` with an element type, so `app.buttons` means "every button anywhere in the app's element tree". The **string subscript** narrows that query: `app.buttons["payButton"]` returns an element whose identifying properties match `"payButton"`. Apple's documentation lists those properties: `identifier`, `title`, `label`, `value` or `placeholderValue`. That breadth is handy when you are exploring, and it is also why identifiers are the safer thing to pass. | You match on | Set by | Changes when | |---|---|---| | `identifier` | the developer, in code | a developer renames it | | `label` | usually the visible text | copy is edited or the app is localized | | index in a list | the layout | rows are added, removed or reordered | ## Setting identifiers in the app The identifier lives in the app's code, not the test's. In UIKit it is the `accessibilityIdentifier` property, which is `nil` by default. In SwiftUI it is the `accessibilityIdentifier(_:)` modifier. A good identifier names the element's role (`payButton`, `zoneRow-4021`), not its looks. Xcode's UI recording often offers several queries for the same element; Apple's recording guide says to pick the one that best represents the element's meaning instead of, for example, its position in a list. ## Tapping and typing 1. **`tap()`** sends a tap to a hittable point computed for the element. If the element is inside a scroll view but offscreen, the framework first tries to scroll it onscreen. 2. **`typeText(_:)`** types a string into the element. The element or one of its descendants must have keyboard focus, or XCUITest raises an error. In practice you call `tap()` on the field first, which brings up the keyboard and gives it focus. 3. When an event method runs, the element is resolved. If the query matches **zero or several** elements, an error is raised, so an identifier that two views share breaks the test. A test like the one in the code example searches for a zone, taps its row and waits for the next screen. It never refers to a label, so translating the app or rewording a button does not break it. ## What tends to go wrong - **Querying by visible text.** `app.buttons["Pay"]` works until someone changes the copy to "Pay now" or runs the suite in another language. - **Typing without focus.** Calling `typeText(_:)` before the field has focus raises an error; XCUITest does not tap the field for you. - **Reusing one identifier.** Two cells both called `zoneRow` make the subscript ambiguous; add the zone number or another stable key. - **Using the wrong type.** A table row is a `cell`, not a `button`, so `app.buttons["zoneRow-4021"]` finds nothing even though the identifier is right. `debugDescription` on the app prints the element tree, with each element's type, when you are not sure. ## Why this matters at screening level Interviewers ask this because it shows whether you have written a UI test that survives a redesign. The answer they want has three parts: the query starts from the application proxy, the identifier comes from the app's code, and typing needs focus. Knowing that the subscript also matches labels and values explains why a test that "worked yesterday" can suddenly match the wrong element.

  • The zone row has the identifier zoneRow-4021, but app.buttons["zoneRow-4021"] never exists. Why?
    The type-named query filters by element type before the subscript checks the identifier. A table or collection row is reported as a cell, so `app.buttons` never contains it. Query `app.cells["zoneRow-4021"]`, or `app.descendants(matching: .any)["zoneRow-4021"]` while exploring, and print `app.debugDescription` to see each element's type.
  • How do you tap a spot on a map view that has no element of its own?
    Make a coordinate relative to an element that does exist: `app.maps.firstMatch.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap()`. The offset is multiplied by the element's frame size and added to its origin, so 0.5, 0.5 is the centre. It is a last resort, because a coordinate breaks when the layout moves.

  • Querying buttons by their visible title text in every test
  • Believing the string subscript matches only the accessibility identifier
  • Calling typeText(_:) without first giving the field keyboard focus
  • Giving every row in a list the same identifier
  • Thinking the test can set identifiers itself without app code changes
open as a page

In XCUITest, how do launchArguments and launchEnvironment put the app into a known state, and why can't the test set that state directly?

level: middleimportance: must knowfreq 68%

basics

~20 s

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

open as a page

In XCUITest, why use waitForExistence(timeout:) instead of sleep, and why can an element that exists still fail isHittable?

level: middleimportance: must knowfreq 75%

basics

~20 s

waitForExistence(timeout:) returns true as soon as the element exists and false at the timeout, so a test waits only as long as it needs. exists means the element is in the UI tree; isHittable also needs it onscreen and not covered.

open as a page

In XCUITest, how do you capture a screenshot of a receipt screen and keep it in the test results even when the test passes?

level: middleimportance: should knowfreq 32%

basics

~10 s

Call screenshot() on an XCUIElement or on XCUIScreen.main, wrap the XCUIScreenshot in XCTAttachment(screenshot:), and add it to the test. Set lifetime to .keepAlways, because the default .deleteOnSuccess throws it away when the test passes.

open as a page

An XCUITest tapping app.buttons["payButton"] fails now and then because the query matches two buttons; why does that happen, and how do you fix it?

level: seniorimportance: should knowfreq 55%

basics

~20 s

tap() resolves the query when it runs, and several matches raise an error. A second view sharing the identifier, like a sheet still animating away, causes it. Wait for that view to go, scope the query, or make identifiers unique.

open as a page

In XCUITest, a system location-permission alert appears while the map loads and blocks the next tap; how does addUIInterruptionMonitor(withDescription:handler:) handle it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

addUIInterruptionMonitor(withDescription:handler:) registers a handler that XCUITest calls when interrupting UI blocks an action the test attempts. The handler taps a button on the alert and returns true; it doesn't run just because an alert appeared, so the next interaction triggers it.

open as a page