0Pricing
Swift Academy · Lezione

Testare il codice async (XCTest)

Scriva async tests con XCTest: contrassegni i test come async , utilizzi await e throws , verifichi fallimenti e timeout e controlli i risultati della concorrenza strutturata.

Testare il codice async (XCTest) è una lezione Swift Academy gratuita su CoddyKit. Questa è la lezione 3 di 3. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Swift Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Swift Academy include 3 lezioni in totale.

Test asincroni: nozioni di base

XCTest supporta i test async. Mantenga i test brevi e deterministici:

  • Dichiari test async e usi await
  • Usi throws e do/catch per gestire gli errori
  • Sostituisca le pause con piccoli fake/stub

Caso di successo asincrono

Contrassegni il test con async e chiami il SUT con await. Scriva normali asserzioni come 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 e asserzioni

Usi test async throws. Per errori specifici, li intercetti ed esegua il pattern matching per mantenere chiara l'intenzione.

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

Risultati paralleli

La concorrenza strutturata è facile da testare: usi async let e verifichi il risultato finale. Mantenga i ritardi minimi per evitare test instabili.

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

Test dei timeout

Testi i timeout mettendo l'operazione in gara con una breve pausa. Usi durate molto brevi per mantenere i test rapidi e stabili.

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)

Per i callback meno recenti, continui a usare expectation/wait. Per il nuovo codice, preferisca i test async.

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

Stile moderno per i test async

Verifica rapida: Qual è la procedura consigliata per testare una funzione async?

Riepilogo

Riepilogo: Usi metodi XCTest async con await, verifichi i percorsi di successo e di errore, mantenga i ritardi minimi e riservi le expectations ai callback legacy.

Domande Frequenti

La lezione «Testare il codice async (XCTest)» è gratuita?

Sì — il testo completo di «Testare il codice async (XCTest)» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Swift Academy, passa a CoddyKit PRO. Il corso Swift Academy include 3 lezioni in totale.

Cosa imparerò in «Testare il codice async (XCTest)»?

Scriva async tests con XCTest: contrassegni i test come async , utilizzi await e throws , verifichi fallimenti e timeout e controlli i risultati della concorrenza strutturata. Eserciti Swift Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Swift Academy?

Non è richiesta alcuna esperienza precedente. Swift Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 3.

Quanto tempo richiede la lezione «Testare il codice async (XCTest)»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Swift Academy?

Sì. Ogni lezione Swift Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Producer/consumer, pipeline e timeout
  2. Collegare callback legacy/Combine ad async/await
  3. Testare il codice async (XCTest)
← Torna a Swift Academy