skip to content

An XCTest callback test passes even when its completion handler never runs, and later raises an exception when the handler fires twice; what is wrong with its expectations?

level: seniorimportance: should knowfreq 60%

answer

  1. nothing waited, nothing proven
  2. which waits see which expectations
  3. count of fulfil calls expected
  4. convenience expectations assert on over-fulfil
  5. inverted expectations prove absence

basics

~20 s

The test never really waits on the expectation its callback fulfils, so it ends first and passes vacuously. The exception comes from fulfilling an expectation more often than expectedFulfillmentCount allows: expectation(description:) sets assertForOverFulfill to true.

solid answer

~40 s

A callback test proves nothing unless it waits on the expectation the callback fulfils. Common gaps: no wait at all; waiting on a different array; or calling `waitForExpectations(timeout:)` on an expectation built with `XCTestExpectation(description:)`, which that method does not wait on. The test returns, nothing fails, and assertions in the callback run after the test has ended, if ever. The exception has a separate cause. `expectation(description:)` sets `assertForOverFulfill` to `true` with an `expectedFulfillmentCount` of 1, so a second `fulfill()` from a cache-then-network client raises. If two calls are the contract, set `expectedFulfillmentCount = 2`; if one is, the client has a bug. To prove a callback never happens, use an expectation with `isInverted = true`.

code

swift · 27 lines
swift
import XCTest

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

final class CachedRecordClient: Sendable {
    // Contract: calls back twice, cached records first, then fresh ones.
    func fetchRecords(completion: @escaping @Sendable ([ServiceRecord]) -> Void) {
        DispatchQueue.global().async {
            completion([ServiceRecord(id: 1)])
            completion([ServiceRecord(id: 1), ServiceRecord(id: 2)])
        }
    }
}

final class CachedRecordClientTests: XCTestCase {
    func testDeliversCachedThenFreshRecords() async {
        let delivered = expectation(description: "cached and fresh records")
        delivered.expectedFulfillmentCount = 2   // without this, the second fulfill() raises

        CachedRecordClient().fetchRecords { records in
            XCTAssertFalse(records.isEmpty)
            delivered.fulfill()
        }

        await fulfillment(of: [delivered], timeout: 2)
    }
}

go deeper

for a junior

Recall that an expectation must be fulfilled inside the callback and waited on with a timeout, or the test proves nothing.

for a middle

Explain expectedFulfillmentCount, why expectation(description:) raises on an extra fulfil while the initializer form does not, and which waits see which expectations.

for a senior

Diagnose a green test that never waited and an over-fulfil exception from a double callback, decide whether the test or the client is wrong, and use inverted expectations to prove absence.

for a principal

Set the team rule for callback tests: convenience-created expectations, explicit wait lists and timeouts, and over-fulfilment treated as a contract question rather than something to silence.

## Two symptoms, two causes A record client in a car-maintenance app calls its completion handler once with cached records and again with fresh ones. Its test shows two symptoms that look related but are not: - **It passes even when the handler never runs.** The expectation is never actually waited on. - **It raises an exception when the handler runs twice.** The expectation is fulfilled more times than it allows. Both come from how `XCTestExpectation` and its waiters work, and both are fixed in the test rather than by adding sleeps. ## Why a test passes vacuously A test method that returns before the callback runs has nothing left to fail. The usual ways to get there: 1. **No wait at all.** The test starts the fetch, puts the assertions inside the callback, and returns. The assertions run later, if ever, after XCTest has finished that test; fulfilling an expectation after its test case has completed is itself an error. 2. **The wrong waiter.** `waitForExpectations(timeout:handler:)` waits only on expectations created with `XCTestCase`'s convenience methods such as `expectation(description:)`. An expectation built with the `XCTestExpectation(description:)` initializer is not waited on by it, so the wait can return without it being fulfilled. 3. **The wrong list.** `wait(for:timeout:)` and `fulfillment(of:timeout:)` wait only on the expectations in the array you pass. 4. **Fulfilling in the wrong place.** Calling `fulfill()` right after starting the work, instead of inside the callback, satisfies the wait immediately. The fix is the same for all four: create the expectation, fulfil it inside the callback after the assertions, and pass that exact expectation to `await fulfillment(of:timeout:)` or, in a synchronous test, `wait(for:timeout:)`. ## Why a second callback raises Every expectation has an `expectedFulfillmentCount`, 1 by default, which must be greater than 0. Whether an extra `fulfill()` raises depends on `assertForOverFulfill`: | Created with | `assertForOverFulfill` default | Extra `fulfill()` | |---|---|---| | `expectation(description:)` and the other `XCTestCase` convenience methods | `true` | raises an exception | | `XCTestExpectation(description:)` initializer | `false` | has no effect | So the cache-then-network client trips the default expectation on its second call. The right fix depends on the contract: - If two callbacks are **intended**, set `expectedFulfillmentCount = 2` so the expectation completes only after both. - If one callback is intended, the exception has found a **real bug** in the client; fix the client, not the test. - Switching to the initializer form only hides the problem, because extra calls are then silently ignored. ## Proving that something does not happen To assert that the handler is not called a third time, or that a failure callback never fires, create an expectation that the unwanted event would fulfil and set `isInverted = true`. The waiter lets the full timeout elapse; fulfilling an inverted expectation fails the test immediately, and its `expectedFulfillmentCount` is ignored. Keep that timeout short, because an inverted wait that passes lasts its full length. ## Order and hangs When the order of callbacks matters, pass `enforceOrder: true`; a fulfilment in the wrong order is reported as a failure. And give every wait an explicit timeout: `fulfillment(of:timeout:)` defaults to `.infinity`, so a handler that never runs keeps the test alive until its execution time allowance, and only when test timeouts are enabled. ## Reading a waiter's result `XCTestCase`'s waits report problems as test failures because the test case is the waiter's delegate. A standalone `XCTWaiter`, useful inside test-support helpers that have no test case at hand, instead returns an `XCTWaiter.Result` from `fulfillment(of:timeout:enforceOrder:)`: | Result | Meaning | |---|---| | `.completed` | every expectation was fulfilled | | `.timedOut` | the timeout expired with expectations unfulfilled | | `.incorrectOrder` | `enforceOrder` was set and the order was violated | | `.invertedFulfillment` | an inverted expectation was fulfilled | | `.interrupted` | an outer waiter timed out first | A helper that ignores this result has recreated the vacuous pass one level down. ## Checklist for a callback test - One expectation per event you care about, fulfilled inside the callback. - Assertions before `fulfill()`. - The exact expectations passed to the wait, with an explicit timeout. - `expectedFulfillmentCount` set when several calls are the contract. - An inverted expectation for anything that must not happen.

  • Why not create the expectation with XCTestExpectation(description:) so the second fulfill() stops raising?
    Because that only silences the signal. Initializer-created expectations default `assertForOverFulfill` to `false`, so extra calls have no effect, and a client that wrongly calls back twice still passes. Decide the contract: set `expectedFulfillmentCount` to the intended number of calls, or fix the client if one call was intended.
  • How do you test that a failure handler is never called?
    Fulfil an expectation inside the failure handler, set its `isInverted` to `true`, and wait on it with a short timeout. The waiter lets the whole timeout pass; if the handler runs and fulfils the expectation, XCTest records a failure. `expectedFulfillmentCount` is ignored for an inverted expectation.
  • A test using waitForExpectations(timeout:) passes instantly. What do you check first?
    How the expectation was created. `waitForExpectations(timeout:handler:)` waits only on expectations made with `XCTestCase` convenience methods such as `expectation(description:)`. One built with the `XCTestExpectation(description:)` initializer is not waited on; pass it explicitly to `wait(for:timeout:)` or `fulfillment(of:timeout:)`.

  • Assertions inside a callback fail the test even if the test never waits.
  • waitForExpectations(timeout:) waits on every expectation the test created.
  • Any extra fulfill() call is ignored, whatever created the expectation.
  • expectedFulfillmentCount = 0 checks that a callback never runs.
  • An inverted expectation passes as soon as the code under test returns.