skip to content

In XCTest, how do you test a service-record client's async fetch method and its completion-handler fetch method?

level: middleimportance: must knowfreq 78%

answer

  1. two shapes of asynchronous code
  2. mark the test async throws
  3. fulfil inside the callback
  4. suspend, don't block, in async tests
  5. unavailable from asynchronous contexts

basics

~20 s

Call the async method from a test marked async throws and assert on the awaited result. For the completion handler, create an expectation, fulfil it in the callback, then await fulfillment(of:timeout:), or call wait(for:timeout:) from a synchronous test.

solid answer

~40 s

For the `async` API, mark the test `async throws`, `try await client.records()`, and assert on the result; XCTest waits for the method to finish and records a thrown error as a failure. Unless the method or class is `@MainActor`, it runs on an arbitrary actor. For the completion handler, create `expectation(description:)`, call `fulfill()` inside the callback after the assertions, and wait: `await fulfillment(of: [delivered], timeout: 2)` in an async test, or `wait(for: [delivered], timeout: 2)` in a synchronous one. `wait(for:timeout:)` is unavailable from asynchronous contexts, with the message to use `await fulfillment(of:timeout:enforceOrder:)` instead: a warning in Swift 5 mode, an error in Swift 6. If the expectation is not fulfilled in time, XCTest records a failure.

code

swift · 32 lines
swift
import XCTest

struct ServiceRecord: Sendable, Equatable { let id: Int }

final class ServiceRecordClient: Sendable {
    func fetchRecords(completion: @escaping @Sendable (Result<[ServiceRecord], Error>) -> Void) {
        DispatchQueue.global().async { completion(.success([ServiceRecord(id: 1)])) }
    }
    func records() async throws -> [ServiceRecord] { [ServiceRecord(id: 1)] }
}

final class ServiceRecordClientTests: XCTestCase {
    func testAsyncFetchReturnsRecords() async throws {
        let records = try await ServiceRecordClient().records()
        XCTAssertEqual(records, [ServiceRecord(id: 1)])
    }

    func testCompletionFetchReturnsRecords() async {
        let delivered = expectation(description: "records delivered")
        ServiceRecordClient().fetchRecords { result in
            XCTAssertEqual(try? result.get(), [ServiceRecord(id: 1)])
            delivered.fulfill()
        }
        await fulfillment(of: [delivered], timeout: 2)
    }

    func testCompletionFetchSynchronousWait() {
        let delivered = expectation(description: "records delivered")
        ServiceRecordClient().fetchRecords { _ in delivered.fulfill() }
        wait(for: [delivered], timeout: 2)
    }
}

go deeper

for a junior

Recall the two tools: an async throws test method for async APIs, and an expectation fulfilled in the callback for completion-handler APIs, always with a timeout.

for a middle

Explain why wait(for:timeout:) is unavailable in async tests and what fulfillment(of:timeout:) does instead, where fulfill() belongs in the callback, and the arbitrary-actor rule.

for a senior

Show you size timeouts for slow CI, enable test timeouts so a missing fulfil cannot hang a run, and choose between bridging a callback to async and testing it with expectations.

for a principal

Decide how the team migrates callback tests as APIs move to async: keep expectations where the callback is the contract, and set the Swift 6 language mode as the gate that removes blocking waits from async tests.

## Two kinds of asynchronous code A service-record client in a car-maintenance app often exposes the same fetch twice: an older `fetchRecords(completion:)` that calls back on some queue, and a newer `records() async throws`. XCTest offers one approach for each: - **Swift concurrency:** mark the test method `async` or `async throws` and `await` the call. - **Everything else** (completion handlers, delegate callbacks, dispatch-queue blocks, Objective-C APIs): create an **expectation**, fulfil it when the work finishes, and wait for it. ## Async test methods An `async throws` test is the simplest form. XCTest runs the method asynchronously and waits until its `await`s complete, so assertions after the `await` see the result. A thrown error is recorded as a test failure, so `try await client.records()` needs no `do`/`catch`. Apple's documentation adds one rule that bites: if neither the method nor its class is marked `@MainActor`, the test runs on an **arbitrary actor**. A test that drives a view model isolated to the main actor should carry the `@MainActor` annotation rather than assume it is already there. ## Expectations for callbacks For `fetchRecords(completion:)`, the steps are: 1. Create the expectation: `let delivered = expectation(description: "records delivered")`. The description appears in the log if it times out. 2. Start the work, and in the callback make the assertions and then call `delivered.fulfill()`. 3. Wait for the expectation with a timeout that the work can meet on a slow CI machine. If the timeout expires before `fulfill()` runs, XCTest records a failure. The waiter reports other problems too, such as an expectation fulfilled out of order when you pass `enforceOrder: true`. ## Waiting: fulfillment(of:timeout:) versus wait(for:timeout:) | API | Where you call it | How it waits | In an async test | |---|---|---|---| | `await fulfillment(of:timeout:enforceOrder:)` | async test methods | suspends the test until fulfilment or timeout | the right call | | `wait(for:timeout:)` | synchronous test methods | does not return until fulfilment or timeout | unavailable | | `waitForExpectations(timeout:handler:)` | synchronous tests, convenience-created expectations only | does not return until fulfilment or timeout | unavailable | `XCTWaiter`'s wait methods and `XCTestCase`'s `wait(for:…)` family are declared **unavailable from asynchronous contexts** with the message "Use await fulfillment(of:timeout:enforceOrder:) instead". With the Xcode 27.1 toolchain that is a warning in the Swift 5 language mode and an error in Swift 6. Both waiting functions are available back to iOS 13, so the choice depends only on whether the test method is async, not on the deployment target. ## Timeouts and hangs `fulfillment(of:timeout:enforceOrder:)` defaults its timeout to `.infinity`. With no timeout, an expectation that is never fulfilled keeps the test running until it reaches its **execution time allowance**, `executionTimeAllowance`, 600 seconds by default, and that allowance applies only when test timeouts are enabled in the test plan or with `xcodebuild`'s `-test-timeouts-enabled` option. Always pass an explicit timeout. ## Expectations for notifications, KVO and predicates `XCTestCase` has convenience methods that create expectations which fulfil themselves when something observable happens, so the test needs no callback of its own: - `expectation(forNotification:object:handler:)` fulfils when a matching notification is posted, for example a "records updated" notification the client posts after saving. - `keyValueObservingExpectation(for:keyPath:expectedValue:)`, and the key-path form `expectation(that:on:options:willEqual:)`, fulfil when an observed property reaches a value. - `expectation(for:evaluatedWith:handler:)` fulfils when a predicate becomes true for an object. They are waited on exactly like the expectation from `expectation(description:)`. ## Bridging instead of expecting When you own the client, another route is to wrap the completion handler with `withCheckedThrowingContinuation` and test the resulting async function; the bridging itself belongs to the material on Swift continuations. Expectations remain the tool when the callback API is what you must verify. ## Common mistakes - Calling `wait(for:timeout:)` inside an `async` test and silencing the warning, then hitting a compile error under Swift 6. - Fulfilling the expectation before the assertions, so a failing assertion runs after XCTest has stopped waiting. - Omitting the timeout and leaving a broken fetch to hang the run. - Forgetting `@MainActor` on a test that drives main-actor state.

  • What happens if you call wait(for:timeout:) inside an async test method?
    The compiler flags it: the method is unavailable from asynchronous contexts, with the message "Use await fulfillment(of:timeout:enforceOrder:) instead". In the Swift 5 language mode that is a warning saying it becomes an error in Swift 6; in Swift 6 it is an error. The fix is `await fulfillment(of: [expectation], timeout: …)`.
  • Why should the assertions in a completion handler come before fulfill()?
    Calling `fulfill()` lets the waiting test continue and possibly finish. Assertions placed after it may run after the test has moved on, so a failure is not tied to the right moment of the test. Assert first, then fulfil, so the test cannot end before its checks have run.
  • When do you pass enforceOrder: true?
    When the order of callbacks is part of the contract, for example a cached result that must arrive before the fresh one. With `enforceOrder: true`, the waiter requires the expectations to be fulfilled in the order of the array and records a failure when one is fulfilled out of order.

  • An async test should still call wait(for:timeout:) to wait for its expectations.
  • An async test method always runs on the main actor.
  • Without a timeout, fulfillment(of:) fails after a few seconds by default.
  • A test that never waits for its expectation proves the callback ran.
  • fulfillment(of:timeout:) needs a newer deployment target than iOS 17.