TestingMidMCQ

What is `XCTestExpectation` and when do you need it?

Test your knowledge:

Explanation & Code

Answer: XCTestExpectation pauses a test until an async condition is fulfilled or a timeout is reached. Needed for callback-based async code where you can't use async/await.

Code Example:

func test_download_completesSuccessfully() {
    // Create expectation
    let expectation = expectation(description: "download completes")

    downloader.download(url: testURL) { result in
        switch result {
        case .success(let data):
            XCTAssertFalse(data.isEmpty)
        case .failure(let error):
            XCTFail("Expected success, got \(error)")
        }
        expectation.fulfill()  // signal test to continue
    }

    // Wait up to 10 seconds
    waitForExpectations(timeout: 10)
}

// For multiple async operations
func test_multipleDownloads() {
    let exp1 = expectation(description: "download 1")
    let exp2 = expectation(description: "download 2")

    downloader.download(url: url1) { _ in exp1.fulfill() }
    downloader.download(url: url2) { _ in exp2.fulfill() }

    wait(for: [exp1, exp2], timeout: 10)
}

Rate your understanding:

Ready to practice more Testing?

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