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.
Testing async code (XCTest) is a free Swift Academy lesson on CoddyKit — lesson 3 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Async tests: the basics
XCTest supports async tests. Keep tests small and deterministic:
- Declare
asynctests and use await - Use throws and
do/catchfor 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.
Frequently asked questions
Is the “Testing async code (XCTest)” lesson free?
Yes — the full text of “Testing async code (XCTest)” is free to read here on the web, and the Swift Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.
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; this is — lesson 3 of 3, so you can start here or from the beginning and move at your own pace.
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
- Producer/consumer, pipelines, timeouts
- Bridging legacy callbacks/Combine to async/await
- Testing async code (XCTest)