skip to content

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%

answer

  1. elements and screens both provide one
  2. wrap the image in an attachment
  3. add it to the test or an activity
  4. default lifetime deletes it on success
  5. keepAlways to keep a passing run's image

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.

solid answer

~30 s

Screenshots come from `XCUIScreenshotProviding`, which `XCUIElement` (so `XCUIApplication` too) and `XCUIScreen` adopt. `receipt.screenshot()` captures one element's area and `XCUIScreen.main.screenshot()` the whole screen; both return an `XCUIScreenshot` with `image` and `pngRepresentation`. An `XCUIScreenshot` on its own goes nowhere. Wrap it in `XCTAttachment(screenshot:)`, optionally with a `quality:` of `.original`, `.medium` or `.low`, give it a `name`, and add it with `add(_:)` on the test case or on an activity from `XCTContext.runActivity(named:)`. Attachments default to `.deleteOnSuccess`, which keeps them only when the test fails, so a receipt image you want from every run needs `lifetime = .keepAlways`.

code

swift · 21 lines
swift
import XCTest

final class ReceiptScreenshotUITests: XCTestCase {
    @MainActor
    func testKeepsReceiptScreenshot() {
        let app = XCUIApplication()
        app.launch()
        let receipt = app.otherElements["receiptCard"]
        XCTAssertTrue(receipt.waitForExistence(timeout: 10))

        XCTContext.runActivity(named: "Capture receipt") { activity in
            let attachment = XCTAttachment(screenshot: receipt.screenshot(), quality: .medium)
            attachment.name = "Receipt card"
            attachment.lifetime = .keepAlways   // default is .deleteOnSuccess
            activity.add(attachment)
        }

        // Whole screen, kept only if the test fails (the default lifetime).
        add(XCTAttachment(screenshot: XCUIScreen.main.screenshot()))
    }
}

go deeper

for a junior

Recall the chain: screenshot() on an element or XCUIScreen.main, XCTAttachment(screenshot:), then add(_:) on the test.

for a middle

Explain the lifetime default, deleteOnSuccess, and when keepAlways is worth it; name the quality options.

for a senior

Show how you group captures with runActivity(named:) and capture after waits, so a failure report explains itself.

for a principal

Weigh evidence kept from every run against CI storage and review time, and set the default your suite follows.

## Two steps: capture, then attach Taking a screenshot in a UI test is two separate jobs, owned by two layers. 1. **Capture**, by UI automation. The `XCUIScreenshotProviding` protocol has one method, `screenshot()`, which returns an `XCUIScreenshot`. 2. **Keep**, by XCTest. An `XCTAttachment` carries data into the test report, and it only counts once it is added to an *activity*. An `XCUIScreenshot` that you never attach is just an object in the runner's memory. When the test ends it is gone. ## Who can take a screenshot | Provider | What the image shows | |---|---| | `XCUIScreen.main.screenshot()` | the device's whole main screen | | `element.screenshot()` | the area of one element, such as a receipt card | | `app.screenshot()` | the app element's area (`XCUIApplication` is an `XCUIElement`) | The header says capturing an element is equivalent to capturing a screenshot by hand: when another window overlaps the element, the front window appears in the image. So treat an element screenshot as that part of the screen, not as a render of the view by itself. `XCUIScreenshot` exposes two things: - `image`, a `UIImage` on iOS; - `pngRepresentation`, the PNG data. You can't create an `XCUIScreenshot` yourself. Its initializer is unavailable, and only screenshot providers make them. ## Attaching and naming `XCTAttachment(screenshot:)` wraps the screenshot. `XCTAttachment(screenshot:quality:)` also takes an `XCTImageQuality`: - `.original`, lossless PNG; - `.medium`, high-quality lossy JPEG or HEIC; - `.low`, highly compressed lossy JPEG or HEIC. Give the attachment a `name` such as "Receipt card", so a reviewer can find it among dozens. You can also set `userInfo` for extra metadata. Then add it to an activity. `XCTestCase` is itself an activity, so `add(attachment)` inside the test method works. To group a step and its evidence, use `XCTContext.runActivity(named:)`. Its block receives an activity, and attachments added there appear under that named step in the report. An image can also travel with a failure you record yourself. `XCTIssue` takes an `attachments` array when you create it, so a custom issue such as "receipt total missing" can carry the screenshot that shows the screen at that moment. That keeps the evidence next to the message instead of somewhere else in the report. ## The lifetime default This is the part interviewers probe. `XCTAttachment` has a `lifetime` property with two values: | Lifetime | Kept when the test passes | Kept when it fails | |---|---|---| | `.deleteOnSuccess` (default) | no | yes | | `.keepAlways` | yes | yes | The header states the default: attachments are deleted when their test passes, so you only keep evidence from failures. That is usually what you want for screen captures around a failure, and it keeps the results small. When the image is the *point*, set `lifetime = .keepAlways` before adding it. A receipt screen that design or support reviews on each build is one example; a screenshot for each step of a localization pass is another. ## Using screenshots well in a parking-payment suite - **Name each capture by step.** "Zone search", "Duration picker" and "Receipt" read better than "Screenshot 3". - **Capture after a wait.** Take the receipt image after `waitForExistence(timeout:)` on the receipt total, or you photograph a spinner. - **Keep sparingly.** `.keepAlways` on every step of every test fills CI storage quickly; keep it for the images people actually look at. - **Prefer the element when it is enough.** A receipt card crop is smaller and easier to compare than the whole screen. - **Pick the quality on purpose.** `.original` keeps a lossless PNG for pixel-level review; `.medium` or `.low` keeps many step images affordable. ## Mistakes that cost evidence 1. Creating an `XCUIScreenshot` and never wrapping it in an attachment, so nothing reaches the report. 2. Adding an attachment in a passing test with the default lifetime, then wondering where it went. 3. Capturing before the screen settles, so the image shows a spinner or a sheet halfway through its animation. 4. Taking a full-screen capture when a banner or alert from another process sits on top, and blaming the app for it. What Xcode records on its own during a run is set in Xcode's test configuration, which is a separate subject. What this question tests is the API: which types provide `screenshot()`, how an image becomes an attachment, and which default throws a passing test's image away.

  • A screenshot of the receipt card shows part of a banner that slid over it. Is that a bug in screenshot()?
    No. The header says an element screenshot is equivalent to capturing that area by hand, so anything in front of the element appears too. Wait for the banner to disappear with `waitForNonExistence(timeout:)` before capturing, or capture after the app has finished presenting.

  • Expecting an XCUIScreenshot to be saved without attaching it
  • Assuming every attachment is kept when the test passes
  • Believing an element screenshot renders the view without anything on top
  • Setting keepAlways on every capture of every test by default