skip to content

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%

answer

  1. an XCTestCase method, not the element's
  2. runs when an action is blocked
  3. return true when handled
  4. last added is tried first
  5. an expected alert needs no monitor

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.

solid answer

~40 s

`addUIInterruptionMonitor(withDescription:handler:)` is an `XCTestCase` method. Its handler receives the interrupting element, such as the alert, and returns `true` when it cleared it. Monitors don't fire when an alert appears; they run when XCUITest, computing a hit point for the next action, finds the element blocked. So the test must try an interaction after the alert shows. They're tried last-added first until one returns `true`, and are removed when the test ends (or with `removeUIInterruptionMonitor(_:)`). Use one only for alerts with unpredictable timing, like a prompt the map raises as it loads. If an alert always follows a tap, query it, wait for it and tap its button. `resetAuthorizationStatus(for: .location)` before launch makes the prompt appear again.

code

swift · 22 lines
swift
import XCTest

final class NearbyZoneUITests: XCTestCase {
    @MainActor
    func testFindsNearbyZoneAfterLocationPrompt() {
        let app = XCUIApplication()
        app.resetAuthorizationStatus(for: .location)   // prompt shows again

        addUIInterruptionMonitor(withDescription: "Location permission") { alert in
            let allow = alert.buttons
                .matching(NSPredicate(format: "label BEGINSWITH %@", "Allow"))
                .firstMatch
            guard allow.exists else { return false }    // let another monitor try
            allow.tap()
            return true
        }

        app.launch()                                  // map asks for location as it loads
        app.buttons["nearbyZonesButton"].tap()        // blocked tap runs the monitor
        XCTAssertTrue(app.staticTexts["nearestZone"].waitForExistence(timeout: 10))
    }
}

go deeper

for a junior

Recall that the method belongs to XCTestCase and that the handler taps a button and returns true when it cleared the alert.

for a middle

Explain that monitors run only when an action is blocked, and that they form a stack tried from the last one added.

for a senior

Show when not to use one: an alert that always follows a tap is queried and tapped directly, and reset authorization makes prompts repeatable.

for a principal

Weigh general dismiss-anything monitors against specific ones, since a broad handler can hide an alert the test should have failed on.

## What counts as an interruption A **UI interruption** is UI that unexpectedly blocks an element the test is trying to use. Most are alerts and dialogs. Some belong to your app, such as an error alert after a background request fails. Others are drawn on behalf of system services, like the location-permission prompt. The key idea in Apple's documentation is that interruptions are **not deterministic**. If an alert appears in direct response to a test action, it is just part of the UI, and the test should treat it like any other screen. | Situation | Right tool | |---|---| | Tapping Pay always shows the app's confirmation alert | query the alert, `waitForExistence(timeout:)`, tap its button | | The map asks for location at some point while it loads | an interruption monitor | | A network failure alert may or may not appear mid-flow | an interruption monitor | ## Registering a monitor `addUIInterruptionMonitor(withDescription:handler:)` belongs to `XCTestCase`, not to `XCUIApplication`, and like the rest of UI testing it is main-actor isolated. It takes: - a **description**, used for debugging and analysis; - a **handler** that receives an `XCUIElement` for the top-level interrupting UI and returns a `Bool`. It returns an opaque token. XCTest removes monitors automatically when the test finishes; to remove one earlier, pass the token to `removeUIInterruptionMonitor(_:)`. Inside the handler, query *from the element you were given*, for example `alert.buttons`, and tap the button that clears it. A system prompt is not part of your app's tree, so `app.alerts` can't find it. The header notes that a query for UI drawn on behalf of system apps must have the right process at its root. The handler's element already has that root, which is why it is the convenient place to dismiss it. ## When the handler actually runs This is the part that trips up most people. The header says monitors are **not** invoked when an alert appears. They are invoked when the alert interferes with an action the test attempts. In Apple's own sequence: 1. The test launches the app and interacts with it. 2. A dialog appears just as the test is about to tap a button. 3. When XCTest computes a hit point for that button, it finds the dialog and treats it as interrupting UI. 4. The most recently installed monitor runs. If it returns `true`, XCTest computes the hit point again and sends the tap. Two consequences follow: - If the next step is an assertion or a `waitForExistence(timeout:)` instead of an interaction, the monitor may never get its chance, and the wait times out behind the alert. Make sure an interaction comes after the point where the prompt can appear. Some suites add a harmless tap on the app for this; be careful, because when no alert is present that tap lands on whatever is in the middle of the screen. - Monitors form a **stack**: they are tried in reverse order of installation until one returns `true`. A specific monitor that returns `false` passes the interruption on to an older, more general one. ## Making the prompt reproducible Once a run has answered a permission prompt on a simulator or device, the next run may not see it at all. `resetAuthorizationStatus(for:)` on `XCUIApplication`, with an `XCUIProtectedResource` such as `.location`, resets it so the system prompts again the next time the app asks. The app need not be running; if it is, it may be terminated during the reset, so call it before `launch()`. Each test then meets the same prompt instead of depending on what an earlier run granted. ## The parking-app flow In the code example, the test resets location access, installs a monitor that taps an Allow button on the alert, launches the app, and taps the nearby-zones button. If the prompt is up, that tap is blocked, the monitor clears the alert, and the tap goes through. The handler returns `false` when it finds no matching button, so a different alert falls through to any other monitor. The button text is the system's localized copy, so this monitor assumes a fixed test language. ## Keeping this in its lane Which permission paths to cover (grant, deny, revoke mid-use) is test design. Here the subject is the mechanism: who owns the method, when the handler runs, how monitors stack, and when not to use one.

  • Your monitor is installed, the alert is on screen, and waitForExistence(timeout:) for the next screen times out. Why?
    A wait is not an interaction, so nothing tried to use a blocked element and the monitor never ran. Monitors run when XCUITest computes a hit point for an action and finds UI in the way. Put an interaction after the point where the prompt can appear, such as the tap that opens nearby zones, and the monitor clears the alert first.
  • Why does app.alerts.firstMatch not find the location prompt?
    The prompt is presented on behalf of a system service, not by your app, so it is not in your app's element tree. Queries for such UI need the right process at their root. Inside an interruption handler you already hold the alert element; outside one, you would query an `XCUIApplication` made with `init(bundleIdentifier:)` for the app that presents it.

  • Expecting the monitor to fire the moment the alert appears
  • Using an interruption monitor for an alert that always follows a tap
  • Calling addUIInterruptionMonitor on the XCUIApplication instance
  • Returning true from a handler that did not clear anything
  • Querying app.alerts for a prompt that a system service presents