TestingMidOpen-ended

How do you test async code in XCTest?

Explanation & Code

Answer: Swift's async/await is directly supported in XCTest — mark your test function as async throws and await the result.

Code Example:

class UserServiceTests: XCTestCase {

    // Modern — async/await (iOS 15.0+, Xcode 13.2+)
    func test_fetchUser_returnsUser() async throws {
        let mockClient = MockHTTPClient()
        mockClient.mockData = try JSONEncoder().encode(User.mock())

        let service = UserService(client: mockClient)
        let user = try await service.fetchUser(id: 1)

        XCTAssertEqual(user.name, "Alice")
    }

    // Legacy — XCTestExpectation for callback-based async
    func test_fetchUser_callsCompletion() {
        let expectation = expectation(description: "fetch completes")

        service.fetchUser(id: 1) { user in
            XCTAssertNotNil(user)
            expectation.fulfill()
        }

        waitForExpectations(timeout: 5)
    }
}

Rate your understanding:

Ready to practice more Testing?

Test yourself with our interactive quiz mode or browse all curated questions for this topic.