# Swift Testing Framework Entrevista 2026: Macros #expect e #require vs XCTest > Domine o novo Swift Testing Framework para entrevistas iOS: macros #expect e #require, migração do XCTest, padrões avançados e armadilhas comuns. - Published: 2026-03-05 - Updated: 2026-04-29 - Author: SharpSkill - Tags: swift, ios, testing, xctest, interview - Reading time: 14 min --- Apresentado na WWDC 2024 e distribuído com Swift 6 e Xcode 16, o Swift Testing representa uma reinvenção completa do funcionamento dos testes em Swift. Esse framework substitui as mais de 40 asserções do XCTest por apenas duas macros: `#expect` e `#require`. Os entrevistadores agora avaliam regularmente esse conhecimento durante entrevistas técnicas iOS. > **Formato do guia** > > Cada seção espelha uma pergunta de entrevista técnica com respostas detalhadas e código funcional. A progressão avança de conceitos fundamentais até padrões avançados. ## Fundamentos do Swift Testing ### Pergunta 1: Quais são as principais diferenças entre Swift Testing e XCTest? O Swift Testing traz cinco mudanças fundamentais em comparação ao XCTest: 1. **Sintaxe declarativa**: atributo `@Test` em vez de prefixos `test` 2. **Duas macros universais**: `#expect` e `#require` substituem mais de 40 asserções 3. **Paralelo por padrão**: todos os testes rodam simultaneamente 4. **Suporte async nativo**: integração completa com Swift Concurrency 5. **Multiplataforma**: funciona em plataformas Apple, Linux e Windows ```swift // TestComparison.swift 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) } ``` A diferença principal está na expressividade: o Swift Testing usa expressões Swift padrão em vez de asserções especializadas, tornando os testes mais legíveis e as mensagens de erro mais informativas. ### Pergunta 2: Como funciona a macro #expect? A macro `#expect` valida que uma expressão booleana seja verdadeira. Ela captura automaticamente os valores avaliados para fornecer mensagens de erro detalhadas. Diferentemente de `XCTAssert`, usa sintaxe Swift nativa. ```swift // ExpectMacroBasics.swift 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 uma `#expect` falha, o teste continua a execução. Essa característica permite coletar várias falhas em uma única rodada, facilitando o diagnóstico. ### Pergunta 3: Qual a diferença entre #expect e #require? A diferença fundamental está no comportamento após uma falha: - `#expect`: registra a falha e **continua** a execução - `#require`: registra a falha e **interrompe** o teste imediatamente `#require` precisa sempre ser usado com `try` porque pode lançar um erro. ```swift // ExpectVsRequire.swift 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") } ``` Na prática, `#require` substitui perfeitamente `XCTUnwrap` para o desempacotamento seguro de optionals. > **Regra de ouro** > > Use `#require` quando os passos seguintes dependem do resultado (desempacotamento, pré-condições). Use `#expect` para verificações independentes que podem falhar sem bloquear o resto do teste. ## Padrões avançados com #require ### Pergunta 4: Como usar #require para desempacotar optionals? `#require` brilha no desempacotamento de optionals. Retorna o valor não-opcional se existir, ou faz o teste falhar imediatamente se for `nil`. ```swift // RequireUnwrapping.swift 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) } ``` Essa abordagem elimina pirâmides de `guard let` e torna o código dos testes linear e legível. ### Pergunta 5: Como verificar que uma função lança um erro? O Swift Testing oferece `#expect(throws:)` para verificar que uma função lança um erro específico. ```swift // ErrorTesting.swift 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) } } ``` Essa sintaxe substitui `XCTAssertThrowsError` com uma API mais clara e type-safe. ## Organização dos testes com @Test e @Suite ### Pergunta 6: Como organizar testes com @Suite? `@Suite` agrupa logicamente testes relacionados. Diferente de `XCTestCase`, não exige herança de classe. ```swift // TestSuiteOrganization.swift 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 } } } ``` As suites permitem rodar subconjuntos de testes e organizar relatórios de forma legível. ### Pergunta 7: Como usar traits para configurar testes? Os traits modificam o comportamento dos testes: condições de execução, tags, timeouts, etc. ```swift // TestTraits.swift 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 } ``` Os traits tornam os testes autodocumentados e permitem execução seletiva via linha de comando. ## Testes parametrizados ### Pergunta 8: Como criar testes parametrizados? O Swift Testing permite rodar o mesmo teste com diferentes entradas via parâmetros. ```swift // ParameterizedTests.swift 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) } ``` Cada combinação de parâmetros gera um teste independente, facilitando a identificação dos casos que falham. ### Pergunta 9: Como testar código assíncrono? O Swift Testing integra async/await de forma nativa, simplificando drasticamente os testes assíncronos. ```swift // AsyncTesting.swift 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 } ``` > **Paralelismo padrão** > > O Swift Testing roda os testes em paralelo por padrão. Para testes que modificam estado compartilhado, use `.serialized` na suite ou isole o estado com actors. ## Migração de XCTest para Swift Testing ### Pergunta 10: Como migrar progressivamente do XCTest? Os dois frameworks coexistem no mesmo projeto. Uma migração progressiva é recomendada. ```swift // MigrationStrategy.swift 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:)` | ### Pergunta 11: Quais recursos do XCTest ainda não estão no Swift Testing? O Swift Testing (Swift 6) ainda não cobre todos os casos de uso do XCTest. ```swift // MissingFeatures.swift // ❌ 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") } ``` Para projetos com testes UI ou de performance, mantenha XCTest para esses casos específicos. ## Perguntas pegadinhas de entrevista ### Pergunta 12: Por que #require precisa de try mas #expect não? `#require` pode lançar um erro caso a condição falhe porque precisa interromper o teste. `#expect` apenas registra a falha e continua, então não lança nada. ```swift // RequireTryExplanation.swift 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(_ value: T?) throws -> T ``` Essa distinção arquitetural permite ao compilador garantir o tratamento correto de falhas. ### Pergunta 13: Como o Swift Testing gerencia paralelismo? Por padrão, todos os testes rodam em paralelo, o que acelera as suites mas exige isolamento adequado do estado. ```swift // ParallelismHandling.swift 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) } } ``` O trait `.serialized` garante a execução sequencial de uma suite inteira. ### Pergunta 14: Como usar confirmations para callbacks? Para APIs com callbacks (não async), o Swift Testing oferece `confirmation`. ```swift // ConfirmationPattern.swift import Testing // Legacy service with callback class LegacyService { func fetchData(completion: @escaping (Result) -> 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` substitui elegantemente `XCTestExpectation` e `wait(for:timeout:)`. ## Conclusão O Swift Testing representa o futuro dos testes em plataformas Apple. As duas macros `#expect` e `#require` simplificam drasticamente a escrita de testes ao mesmo tempo que melhoram a qualidade das mensagens de erro. **Pontos-chave para guardar para entrevistas:** - ✅ `#expect` continua após falha, `#require` interrompe imediatamente - ✅ `#require` exige `try` porque pode lançar erro - ✅ Swift Testing roda em paralelo por padrão - ✅ Os dois frameworks coexistem mas não devem ser misturados no mesmo teste - ✅ XCTest continua necessário para testes UI e de performance - ✅ Os traits permitem configurar finamente o comportamento dos testes - ✅ Os testes parametrizados evitam duplicação de código A migração para o Swift Testing pode ser feita progressivamente, arquivo por arquivo, começando pelos testes mais simples. --- Source: SharpSkill (https://sharpskill.dev), tech interview preparation for your real stack. HTML version of this page: https://sharpskill.dev/pt/blog/ios/swift-testing-framework-macros-expect-require-xctest