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
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)
}
}All lessons in this course
- Producer/consumer, pipelines, timeouts
- Bridging legacy callbacks/Combine to async/await
- Testing async code (XCTest)