Swift Testing Framework Colloquio 2026: Macro #expect e #require vs XCTest

Padroneggia il nuovo Swift Testing Framework per i colloqui iOS: macro #expect e #require, migrazione da XCTest, pattern avanzati ed errori comuni.

Swift Testing Framework con macro #expect e #require per i colloqui iOS

Presentato alla WWDC 2024 e distribuito con Swift 6 e Xcode 16, Swift Testing rappresenta una completa reinvenzione del modo in cui funzionano i test in Swift. Questo framework sostituisce le oltre 40 asserzioni di XCTest con sole due macro: #expect e #require. Gli intervistatori ora valutano regolarmente questa conoscenza durante i colloqui tecnici iOS.

Formato della guida

Ogni sezione rispecchia una domanda di colloquio tecnico con risposte dettagliate e codice funzionante. La progressione va dai concetti fondamentali ai pattern avanzati.

Fondamenti di Swift Testing

Domanda 1: Quali sono le principali differenze tra Swift Testing e XCTest?

Swift Testing porta cinque cambiamenti fondamentali rispetto a XCTest:

  1. Sintassi dichiarativa: attributo @Test al posto dei prefissi test
  2. Due macro universali: #expect e #require sostituiscono oltre 40 asserzioni
  3. Parallelo di default: tutti i test vengono eseguiti in parallelo
  4. Supporto async nativo: integrazione completa con Swift Concurrency
  5. Multipiattaforma: funziona su piattaforme Apple, Linux e Windows
TestComparison.swiftswift
import XCTest
import Testing

// ❌ Legacy XCTest pattern
class UserServiceXCTests: XCTestCase {
    // Must start with "test"
    func testUserCreation() {
        let user = User(name: "Alice", age: 25)

        // Multiple verbose assertions
        XCTAssertNotNil(user)
        XCTAssertEqual(user.name, "Alice")
        XCTAssertGreaterThan(user.age, 18)
        XCTAssertTrue(user.isValid)
    }
}

// ✅ Modern Swift Testing pattern
@Test("User creation with valid data")
func userCreation() {
    let user = User(name: "Alice", age: 25)

    // Single macro for all verifications
    #expect(user.name == "Alice")
    #expect(user.age > 18)
    #expect(user.isValid)
}

La differenza chiave risiede nell'espressività: Swift Testing utilizza espressioni Swift standard al posto di asserzioni specializzate, rendendo i test più leggibili e i messaggi di errore più informativi.

Domanda 2: Come funziona la macro #expect?

La macro #expect verifica che un'espressione booleana sia vera. Cattura automaticamente i valori valutati per fornire messaggi di errore dettagliati. A differenza di XCTAssert, utilizza la sintassi Swift nativa.

ExpectMacroBasics.swiftswift
import Testing

@Test func basicExpectations() {
    let numbers = [1, 2, 3, 4, 5]
    let user = User(name: "Bob", email: "bob@example.com")

    // Simple comparisons - standard Swift expression
    #expect(numbers.count == 5)
    #expect(user.name == "Bob")

    // Comparisons with operators
    #expect(numbers.first! < numbers.last!)
    #expect(user.email.contains("@"))

    // Nil checking
    #expect(numbers.first != nil)

    // Collection verification
    #expect(numbers.contains(3))
    #expect(!numbers.isEmpty)
}

@Test func expectWithCustomMessage() {
    let balance = 150.0
    let withdrawAmount = 200.0

    // Custom message to clarify intent
    #expect(
        balance >= withdrawAmount,
        "Insufficient funds: balance \(balance) < withdrawal \(withdrawAmount)"
    )
}

Quando una #expect fallisce, il test continua l'esecuzione. Questa caratteristica permette di raccogliere più fallimenti in una singola esecuzione, semplificando la diagnosi.

Domanda 3: Qual è la differenza tra #expect e #require?

La differenza fondamentale riguarda il comportamento dopo un fallimento:

  • #expect: registra il fallimento e continua l'esecuzione
  • #require: registra il fallimento e interrompe immediatamente il test

#require deve sempre essere usato con try perché può lanciare un errore.

ExpectVsRequire.swiftswift
import Testing

struct ApiResponse {
    let data: Data?
    let items: [Item]?
}

@Test func demonstrateExpectContinues() {
    let values = [1, 2, 3]

    // First #expect fails but test continues
    #expect(values.count == 10)  // ❌ Failure recorded

    // These verifications still execute
    #expect(values.first == 1)   // ✅ Success
    #expect(values.last == 3)    // ✅ Success

    // Result: 1 failure, 2 successes in the same test
}

@Test func demonstrateRequireStops() throws {
    let response = ApiResponse(data: nil, items: nil)

    // #require stops immediately if condition fails
    let data = try #require(response.data)  // ❌ Failure and STOP

    // This code NEVER executes if data is nil
    let json = try JSONDecoder().decode(User.self, from: data)
    #expect(json.name == "Alice")
}

Nella pratica, #require sostituisce perfettamente XCTUnwrap per l'unwrapping sicuro degli optional.

Regola d'oro

Utilizza #require quando i passaggi successivi dipendono dal risultato (unwrapping, precondizioni). Utilizza #expect per verifiche indipendenti che possono fallire senza bloccare il resto del test.

Pattern avanzati con #require

Domanda 4: Come usare #require per l'unwrapping degli optional?

#require eccelle nell'unwrapping degli optional. Restituisce il valore non-opzionale se esiste, oppure fa fallire il test immediatamente se è nil.

RequireUnwrapping.swiftswift
import Testing

struct UserProfile {
    let id: Int
    let name: String
    let settings: Settings?
}

struct Settings {
    let theme: String
    let notifications: Bool
}

@Test func unwrapOptionalChain() throws {
    let profile = UserProfile(
        id: 1,
        name: "Alice",
        settings: Settings(theme: "dark", notifications: true)
    )

    // Safe unwrap - stops if nil
    let settings = try #require(profile.settings)

    // Now settings is no longer optional
    #expect(settings.theme == "dark")
    #expect(settings.notifications == true)
}

@Test func unwrapArrayElement() throws {
    let users = ["Alice", "Bob", "Charlie"]

    // Unwrap first element
    let firstUser = try #require(users.first)
    #expect(firstUser == "Alice")

    // Unwrap with safe index
    let secondUser = try #require(users[safe: 1])
    #expect(secondUser == "Bob")
}

@Test func unwrapDictionaryValue() throws {
    let config: [String: Any] = [
        "apiUrl": "https://api.example.com",
        "timeout": 30,
        "retryCount": 3
    ]

    // Unwrap and cast in a single operation
    let apiUrl = try #require(config["apiUrl"] as? String)
    let timeout = try #require(config["timeout"] as? Int)

    #expect(apiUrl.contains("https"))
    #expect(timeout > 0)
}

Questo approccio elimina le piramidi di guard let e rende il codice dei test lineare e leggibile.

Domanda 5: Come verificare che una funzione lanci un errore?

Swift Testing offre #expect(throws:) per verificare che una funzione lanci un errore specifico.

ErrorTesting.swiftswift
import Testing

enum ValidationError: Error, Equatable {
    case emptyName
    case invalidEmail
    case underAge(minimum: Int)
}

struct Validator {
    static func validateUser(name: String, email: String, age: Int) throws {
        guard !name.isEmpty else {
            throw ValidationError.emptyName
        }
        guard email.contains("@") else {
            throw ValidationError.invalidEmail
        }
        guard age >= 18 else {
            throw ValidationError.underAge(minimum: 18)
        }
    }
}

@Test func testThrowsSpecificError() {
    // Verify a specific error is thrown
    #expect(throws: ValidationError.emptyName) {
        try Validator.validateUser(name: "", email: "test@mail.com", age: 25)
    }

    #expect(throws: ValidationError.invalidEmail) {
        try Validator.validateUser(name: "Alice", email: "invalid", age: 25)
    }
}

@Test func testThrowsErrorType() {
    // Verify error type without specific value
    #expect(throws: ValidationError.self) {
        try Validator.validateUser(name: "Bob", email: "bob@mail.com", age: 15)
    }
}

@Test func testThrowsWithInspection() throws {
    // Capture error for detailed inspection
    let error = try #require(
        throws: ValidationError.self
    ) {
        try Validator.validateUser(name: "Charlie", email: "charlie@mail.com", age: 16)
    }

    // Verify error details
    if case .underAge(let minimum) = error {
        #expect(minimum == 18)
    }
}

Questa sintassi sostituisce XCTAssertThrowsError con un'API più chiara e type-safe.

Pronto a superare i tuoi colloqui su iOS?

Pratica con i nostri simulatori interattivi, flashcards e test tecnici.

Organizzazione dei test con @Test e @Suite

Domanda 6: Come organizzare i test con @Suite?

@Suite raggruppa logicamente i test correlati. A differenza di XCTestCase, non richiede ereditarietà di classe.

TestSuiteOrganization.swiftswift
import Testing

// Suite for authentication tests
@Suite("Authentication Tests")
struct AuthenticationTests {

    // Shared property for all tests in the suite
    let authService = AuthService()

    @Test("Login with valid credentials succeeds")
    func loginWithValidCredentials() async throws {
        let result = try await authService.login(
            email: "user@example.com",
            password: "validPass123"
        )

        #expect(result.isSuccess)
        let token = try #require(result.token)
        #expect(!token.isEmpty)
    }

    @Test("Login with invalid password fails")
    func loginWithInvalidPassword() async {
        let result = await authService.login(
            email: "user@example.com",
            password: "wrong"
        )

        #expect(!result.isSuccess)
        #expect(result.error == .invalidCredentials)
    }
}

// Nested suites for hierarchical organization
@Suite("User Management")
struct UserManagementTests {

    @Suite("Creation")
    struct CreationTests {
        @Test func createUserWithValidData() {
            // Creation test
        }

        @Test func createUserWithDuplicateEmail() {
            // Duplicate error test
        }
    }

    @Suite("Deletion")
    struct DeletionTests {
        @Test func deleteExistingUser() {
            // Deletion test
        }

        @Test func deleteNonExistentUser() {
            // Error test
        }
    }
}

Le suite consentono di eseguire sottoinsiemi di test e di organizzare i report in modo leggibile.

Domanda 7: Come usare i trait per configurare i test?

I trait modificano il comportamento dei test: condizioni di esecuzione, tag, timeout, ecc.

TestTraits.swiftswift
import Testing

@Suite("API Integration Tests")
struct APITests {

    // Temporarily disabled test
    @Test(.disabled("Backend under maintenance"))
    func fetchUserProfile() async {
        // Does not execute
    }

    // Conditional test based on platform
    @Test
    @available(iOS 17, *)
    func useNewAPIFeature() {
        // Executes only on iOS 17+
    }

    // Test with tags for filtering
    @Test(.tags(.critical, .network))
    func criticalNetworkOperation() async throws {
        // Tagged test for filtering
    }

    // Test with custom timeout
    @Test(.timeLimit(.minutes(2)))
    func longRunningOperation() async {
        // Must complete within 2 minutes
    }

    // Trait combination
    @Test(
        "Complex data sync",
        .tags(.slow),
        .timeLimit(.minutes(5)),
        .bug("JIRA-1234", "Flaky on CI")
    )
    func complexDataSync() async throws {
        // Test documented with known bug
    }
}

// Custom tag definitions
extension Tag {
    @Tag static var critical: Self
    @Tag static var network: Self
    @Tag static var slow: Self
}

I trait rendono i test autodocumentati e consentono l'esecuzione selettiva da riga di comando.

Test parametrizzati

Domanda 8: Come creare test parametrizzati?

Swift Testing permette di eseguire lo stesso test con input diversi tramite parametri.

ParameterizedTests.swiftswift
import Testing

struct EmailValidator {
    static func isValid(_ email: String) -> Bool {
        let pattern = #"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"#
        return email.range(of: pattern, options: .regularExpression) != nil
    }
}

// Parameterized test with a collection
@Test(arguments: [
    "user@example.com",
    "test.name@domain.org",
    "contact@company.co.uk"
])
func validEmailsAreAccepted(email: String) {
    #expect(EmailValidator.isValid(email))
}

@Test(arguments: [
    "invalid",
    "@nodomain.com",
    "no@tld",
    "spaces in@email.com"
])
func invalidEmailsAreRejected(email: String) {
    #expect(!EmailValidator.isValid(email))
}

// Test with tuples for input/output cases
@Test(arguments: [
    ("hello", "HELLO"),
    ("World", "WORLD"),
    ("Swift", "SWIFT")
])
func uppercaseConversion(input: String, expected: String) {
    #expect(input.uppercased() == expected)
}

// Test with Cartesian product of two collections
@Test(arguments: [1, 2, 3], ["a", "b"])
func combinationTest(number: Int, letter: String) {
    // Runs for (1,"a"), (1,"b"), (2,"a"), (2,"b"), (3,"a"), (3,"b")
    let combined = "\(number)\(letter)"
    #expect(combined.count == 2)
}

Ogni combinazione di parametri genera un test indipendente, facilitando l'identificazione dei casi falliti.

Domanda 9: Come testare codice asincrono?

Swift Testing integra nativamente async/await, semplificando drasticamente i test asincroni.

AsyncTesting.swiftswift
import Testing

actor DataStore {
    private var items: [String] = []

    func add(_ item: String) {
        items.append(item)
    }

    func getAll() -> [String] {
        items
    }

    func clear() {
        items.removeAll()
    }
}

@Suite("Async Operations")
struct AsyncTests {

    @Test func basicAsyncOperation() async {
        // No need for expectation or wait
        let result = await fetchData()
        #expect(!result.isEmpty)
    }

    @Test func asyncWithTimeout() async throws {
        // Use Task.sleep to simulate delay
        try await Task.sleep(for: .milliseconds(100))

        let data = await loadConfiguration()
        let config = try #require(data)
        #expect(config.isValid)
    }

    @Test func testActorIsolation() async {
        let store = DataStore()

        // Operations on actor sequentially
        await store.add("Item 1")
        await store.add("Item 2")

        let items = await store.getAll()
        #expect(items.count == 2)
        #expect(items.contains("Item 1"))
    }

    @Test func testConcurrentOperations() async {
        let store = DataStore()

        // Concurrent execution with TaskGroup
        await withTaskGroup(of: Void.self) { group in
            for i in 1...10 {
                group.addTask {
                    await store.add("Item \(i)")
                }
            }
        }

        let items = await store.getAll()
        #expect(items.count == 10)
    }
}

// Async helpers for tests
func fetchData() async -> [String] {
    try? await Task.sleep(for: .milliseconds(50))
    return ["data1", "data2"]
}

func loadConfiguration() async -> Configuration? {
    Configuration(isValid: true)
}

struct Configuration {
    let isValid: Bool
}
Parallelismo predefinito

Swift Testing esegue i test in parallelo per impostazione predefinita. Per i test che modificano stato condiviso, usa .serialized sulla suite oppure isola lo stato con gli actor.

Migrazione da XCTest a Swift Testing

Domanda 10: Come migrare progressivamente da XCTest?

I due framework coesistono nello stesso progetto. È consigliata una migrazione progressiva.

MigrationStrategy.swiftswift
import XCTest
import Testing

// ⚠️ CRITICAL RULE: Never mix frameworks in the same test

// ❌ INCORRECT - Mixing forbidden
class BadMixedTest: XCTestCase {
    func testMixed() {
        #expect(true)  // Does not work in XCTestCase
    }
}

// ✅ CORRECT - Pure XCTest for existing tests
class LegacyUserTests: XCTestCase {
    func testUserCreation() {
        let user = User(name: "Test")
        XCTAssertNotNil(user)
        XCTAssertEqual(user.name, "Test")
    }
}

// ✅ CORRECT - Swift Testing for new tests
@Suite("User Tests - Modern")
struct ModernUserTests {
    @Test func userCreation() {
        let user = User(name: "Test")
        #expect(user.name == "Test")
    }
}

// Migration strategy by file
// 1. Identify tests to migrate (start with simplest)
// 2. Create new file with @Suite
// 3. Rewrite tests one by one
// 4. Delete old XCTest file once validated

| XCTest | Swift Testing | |--------|---------------| | XCTAssertTrue(x) | #expect(x) | | XCTAssertFalse(x) | #expect(!x) | | XCTAssertEqual(a, b) | #expect(a == b) | | XCTAssertNil(x) | #expect(x == nil) | | XCTAssertNotNil(x) | #expect(x != nil) | | XCTUnwrap(x) | try #require(x) | | XCTAssertThrowsError | #expect(throws:) |

Domanda 11: Quali funzionalità di XCTest mancano ancora in Swift Testing?

Swift Testing (Swift 6) non copre ancora tutti i casi d'uso di XCTest.

MissingFeatures.swiftswift
// ❌ NOT SUPPORTED: Performance tests
// Stick with XCTest for measuring performance
class PerformanceTests: XCTestCase {
    func testPerformance() {
        measure {
            // Code to measure
            _ = (0..<1000).map { $0 * 2 }
        }
    }
}

// ❌ NOT SUPPORTED: UI tests (XCUITest)
// Continue using XCUITest for interface tests
class UITests: XCTestCase {
    func testLoginFlow() {
        let app = XCUIApplication()
        app.launch()
        // UI tests...
    }
}

// ✅ SUPPORTED: Async integration tests
@Test func integrationTest() async throws {
    let api = APIClient()
    let response = try await api.fetchUsers()
    #expect(!response.isEmpty)
}

// ✅ SUPPORTED: Mocking with protocols
@Test func mockingWithProtocols() async {
    let mockService = MockUserService()
    let viewModel = UserViewModel(service: mockService)

    await viewModel.loadUser(id: 1)

    #expect(viewModel.user?.name == "Mock User")
}

Per i progetti con test UI o di performance, mantieni XCTest per quei casi specifici.

Pronto a superare i tuoi colloqui su iOS?

Pratica con i nostri simulatori interattivi, flashcards e test tecnici.

Domande insidiose da colloquio

Domanda 12: Perché #require richiede try ma #expect no?

#require può lanciare un errore se la condizione fallisce perché deve interrompere il test. #expect registra solo il fallimento e continua, quindi non lancia nulla.

RequireTryExplanation.swiftswift
import Testing

@Test func explainTryRequirement() throws {
    let optionalValue: String? = nil

    // #expect returns Void - no error thrown
    // Test continues even if it fails
    #expect(optionalValue != nil)  // No try

    // #require can throw ExpectationFailedError
    // Test stops if it fails
    // Must be marked with try
    let value = try #require(optionalValue)  // Requires try

    // If we reach here, optionalValue was not nil
    #expect(!value.isEmpty)
}

// The internal signature resembles:
// func #expect(_ condition: Bool) -> Void
// func #require<T>(_ value: T?) throws -> T

Questa distinzione architetturale permette al compilatore di garantire una corretta gestione dei fallimenti.

Domanda 13: Come gestisce Swift Testing il parallelismo?

Per impostazione predefinita, tutti i test vengono eseguiti in parallelo, il che velocizza le suite ma richiede un corretto isolamento dello stato.

ParallelismHandling.swiftswift
import Testing

// ❌ PROBLEM: Mutable shared state
var sharedCounter = 0  // Dangerous in parallel!

@Suite("Problematic Parallel Tests")
struct ProblematicTests {
    @Test func incrementCounter1() {
        sharedCounter += 1  // Race condition!
    }

    @Test func incrementCounter2() {
        sharedCounter += 1  // Race condition!
    }
}

// ✅ SOLUTION 1: Force sequential execution
@Suite("Sequential Tests", .serialized)
struct SequentialTests {
    static var counter = 0

    @Test func first() {
        Self.counter += 1
        #expect(Self.counter == 1)
    }

    @Test func second() {
        Self.counter += 1
        #expect(Self.counter == 2)
    }
}

// ✅ SOLUTION 2: Isolate state per test
@Suite("Isolated Tests")
struct IsolatedTests {
    @Test func independentTest1() {
        var localCounter = 0
        localCounter += 1
        #expect(localCounter == 1)
    }

    @Test func independentTest2() {
        var localCounter = 0
        localCounter += 1
        #expect(localCounter == 1)
    }
}

// ✅ SOLUTION 3: Use actor for shared state
actor TestState {
    var value = 0

    func increment() -> Int {
        value += 1
        return value
    }
}

@Suite("Actor-based Tests")
struct ActorTests {
    let state = TestState()

    @Test func safeIncrement() async {
        let result = await state.increment()
        #expect(result > 0)
    }
}

Il trait .serialized garantisce l'esecuzione sequenziale di un'intera suite.

Domanda 14: Come usare le confirmation per i callback?

Per le API con callback (non async), Swift Testing offre confirmation.

ConfirmationPattern.swiftswift
import Testing

// Legacy service with callback
class LegacyService {
    func fetchData(completion: @escaping (Result<String, Error>) -> Void) {
        DispatchQueue.global().asyncAfter(deadline: .now() + 0.1) {
            completion(.success("Data loaded"))
        }
    }
}

@Test func testCallbackWithConfirmation() async {
    let service = LegacyService()

    // confirmation waits for it to be called
    await confirmation("Data callback received") { confirm in
        service.fetchData { result in
            if case .success(let data) = result {
                #expect(data == "Data loaded")
                confirm()  // Signals callback was executed
            }
        }
    }
}

// For callbacks called multiple times
@Test func testMultipleCallbacks() async {
    let publisher = EventPublisher()

    // expectedCount specifies expected call count
    await confirmation("Events received", expectedCount: 3) { confirm in
        publisher.onEvent = { event in
            #expect(!event.isEmpty)
            confirm()  // Called 3 times
        }

        publisher.emit("Event 1")
        publisher.emit("Event 2")
        publisher.emit("Event 3")
    }
}

class EventPublisher {
    var onEvent: ((String) -> Void)?

    func emit(_ event: String) {
        DispatchQueue.global().async {
            self.onEvent?(event)
        }
    }
}

confirmation sostituisce elegantemente XCTestExpectation e wait(for:timeout:).

Conclusione

Swift Testing rappresenta il futuro dei test sulle piattaforme Apple. Le due macro #expect e #require semplificano drasticamente la scrittura dei test migliorando al contempo la qualità dei messaggi di errore.

Punti chiave da ricordare per i colloqui:

  • #expect continua dopo un fallimento, #require si interrompe immediatamente
  • #require richiede try perché può lanciare un errore
  • ✅ Swift Testing viene eseguito in parallelo per impostazione predefinita
  • ✅ I due framework coesistono ma non devono essere mescolati nello stesso test
  • ✅ XCTest rimane necessario per i test UI e di performance
  • ✅ I trait permettono di configurare finemente il comportamento dei test
  • ✅ I test parametrizzati evitano la duplicazione del codice

La migrazione a Swift Testing può essere effettuata progressivamente, file per file, partendo dai test più semplici.

Inizia a praticare!

Metti alla prova le tue conoscenze con i nostri simulatori di colloquio e test tecnici.

Tag

#swift
#ios
#testing
#xctest
#interview

Condividi

Articoli correlati