0Pricing
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.

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)
    }
}

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