Swift Academy · Lesson

Testing async code (XCTest)

Write async tests with XCTest: mark tests async , use await and throws , test failures and timeouts, and assert structured concurrency results.

Lesson 3 of 38 steps

Testing async code (XCTest) is a free Swift Academy lesson on CoddyKit. This is lesson 3 of 3. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 3 lessons in total.

Async tests: the basics

XCTest supports async tests. Keep tests small and deterministic:

  • Declare async tests and use await
  • Use throws and do/catch for failures
  • Replace sleeps with tiny fakes/stubs

Async success case

Mark the test async and call the SUT with await. Write normal assertions like XCTAssertEqual.

import XCTest
import Foundation

// System Under Test (SUT)
func fetchValue() async -> Int {
    try? await Task.sleep(nanoseconds: 50_000_000)
    return 42
}

final class AsyncBasicsTests: XCTestCase {
    func testFetchValue_returns42() async {
        let v = await fetchValue()
        XCTAssertEqual(v, 42)
    }
}

Async throws & assertions

Use async throws tests. For specific errors, catch and pattern-match to keep intent clear.

import XCTest

enum NetError: Error { case offline }

func loadNumber(online: Bool) async throws -> Int {
    try await Task.sleep(nanoseconds: 30_000_000)
    if !online { throw NetError.offline }
    return 7
}

final class AsyncThrowingTests: XCTestCase {
    func testLoadNumber_success() async throws {
        let n = try await loadNumber(online: true)
        XCTAssertEqual(n, 7)
    }

    func testLoadNumber_offline_throws() async {
        do {
            _ = try await loadNumber(online: false)
            XCTFail("Expected error")
        } catch NetError.offline {
            // expected
        } catch {
            XCTFail("Unexpected error: \\(error)")
        }
    }
}

Parallel results

Structured concurrency is easy to test: use async let and assert the final result. Keep delays tiny to avoid flaky tests.

import XCTest

func compute(_ x: Int) async -> Int {
    try? await Task.sleep(nanoseconds: 10_000_000)
    return x * x
}

final class ParallelTests: XCTestCase {
    func testParallel_asyncLet_sumsSquares() async {
        async let a = compute(2)
        async let b = compute(3)
        let sum = await (a + b)
        XCTAssertEqual(sum, 13) // 4 + 9
    }
}

Timeout testing

Test timeouts by racing the op vs. a short sleep. Use very small durations to keep tests fast and stable.

import XCTest

enum TimeoutError: Error { case timedOut }

func withTimeout<T>(
    seconds: Double,
    operation: @escaping () async throws -> T
) async throws -> T {
    try await withThrowingTaskGroup(of: T.self) { group in
        group.addTask { try await operation() }
        group.addTask {
            try await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))
            throw TimeoutError.timedOut
        }
        let first = try await group.next()!
        group.cancelAll()
        return first
    }
}

final class TimeoutTests: XCTestCase {
    func testTimeout_timesOutFast() async {
        do {
            _ = try await withTimeout(seconds: 0.01) {
                try await Task.sleep(nanoseconds: 50_000_000) // slower than timeout
                return "OK"
            }
            XCTFail("Expected timeout")
        } catch TimeoutError.timedOut {
            // expected
        } catch {
            XCTFail("Unexpected error: \\(error)")
        }
    }
}

Expectations (legacy)

For older callbacks, still use expectation/wait. Prefer async tests for new code.

import XCTest

// Legacy API with a completion handler
func legacyFetch(_ completion: @escaping (String) -> Void) {
    Task { try? await Task.sleep(nanoseconds: 20_000_000); completion("done") }
}

final class ExpectationTests: XCTestCase {
    func testLegacy_withExpectation() {
        let exp = expectation(description: "legacy finishes")
        legacyFetch { value in
            XCTAssertEqual(value, "done")
            exp.fulfill()
        }
        wait(for: [exp], timeout: 1.0)
    }
}

Modern async test style

Quick check: Best practice to test an async function?

Recap

Recap: Use async XCTest methods with await, assert success and failure paths, keep delays tiny, and reserve expectations for legacy callbacks.

Free to start

Learn Swift with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
122
Lessons
409

Frequently Asked Questions

Is the “Testing async code (XCTest)” lesson free?

Yes — any 3 lessons of the Swift Academy learning path, including “Testing async code (XCTest)”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 3 lessons in total.

What will I learn in “Testing async code (XCTest)”?

Write async tests with XCTest: mark tests async , use await and throws , test failures and timeouts, and assert structured concurrency results. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 3.

How long does the “Testing async code (XCTest)” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Producer/consumer, pipelines, timeouts
  2. Bridging legacy callbacks/Combine to async/await
  3. Testing async code (XCTest)
← Back to Swift Academy