Swift Testing Framework

The interviewer asks

“What is the Swift Testing framework?”

How to answer

Swift Testing is Apple's modern, macro-based test framework; it has shipped with Xcode since Xcode 16 and works in both Swift 5 and Swift 6 language modes. A test is any function marked @Test, assertions are just #expect and try #require (which show the actual values on failure), and suites are plain types with a fresh instance per test. Tests run in parallel by default. I use it for all new unit and integration tests and keep XCTest, side by side in the same target, for UI automation and measure {} performance tests.

Key points

  • @Test functions can be async, throws and @MainActor; @Test("Readable name") sets a display name
  • #expect records a failure and continues; try #require stops the test and unwraps optionals
  • Suites: a struct is preferred; setup in init() (can be async throws), teardown in deinit of a final class/actor suite
  • @Test(arguments:): each argument is a separate, re-runnable test case
  • Traits: .tags, .timeLimit, .serialized, .disabled, .enabled(if:), .bug
  • confirmation() for callback events, withKnownIssue for expected failures, Attachment.record (Swift 6.2) for attachments

If they dig deeper

  • Migration: migrate file by file. In Swift 6.4, #expect works inside XCTest tests and XCTAssert inside Swift Testing tests (ST-0021) (asymmetric by default: a failing #expect in XCTest fails the test, but a failing XCTAssert in a @Test is only a warning unless SWIFT_TESTING_XCTEST_INTEROP_MODE=complete).
  • Errors: #expect(throws: MyError.self), #expect(throws: MyError.notFound), #expect(throws: Never.self); the macro returns the caught error.
  • Async: just await the call. confirmation() is not a timed wait; the callback must fire before its closure returns.
  • Exit tests (#expect(processExitsWith:), Swift 6.2) exist only on macOS, Linux and Windows, not iOS.

Common pitfalls

  • Relying on a singleton or UserDefaults.standard in parallel tests, then seeing random failures
  • Using #expect(x != nil) and then force-unwrapping, instead of let x = try #require(x)
  • Treating confirmation() like XCTestExpectation (it doesn't wait for a later callback)
  • Expecting measure {} or UI automation; those stay in XCTest

How to use it

swift
import Testing

extension Tag { @Tag static var pricing: Self }

@Suite("Cart", .tags(.pricing))
struct CartTests {
    let cart: Cart
    init() { cart = Cart() }                         // runs before every test

    @Test("Adding an item stores it") func addingItemStoresIt() throws {
        cart.add(Item(name: "Pen", price: 10))
        let first = try #require(cart.items.first)   // stops here if empty
        #expect(first.name == "Pen")
    }

    @Test(arguments: [1, 2, 5]) func totalScalesWithQuantity(quantity: Int) {
        cart.add(Item(name: "Pen", price: 10), quantity: quantity)
        #expect(cart.total == 10 * quantity)
    }

    @Test(.bug("https://example.com/issues/42", id: 42), .timeLimit(.minutes(1)))
    func checkoutRejectsEmptyCart() {
        #expect(throws: CartError.empty) { try cart.checkout() }
    }

    @Test @MainActor func savingNotifiesDelegate() async {
        let store = DraftStore()
        await confirmation("didSave called") { didSave in
            store.onSave = { _ in didSave() }        // must fire before the closure returns
            store.save("Hello")
        }
    }

    @Test func knownRoundingBug() {
        Attachment.record("2.675", named: "input.txt")   // Swift 6.2
        withKnownIssue("Rounding bug, see #57") { #expect(Price.rounded(2.675) == 2.68) }
    }
}

Best practices

  • Prefer struct suites with setup in init(); class/actor suites only when you need deinit
  • Use try #require for preconditions, #expect for the assertions
  • Inject per-test dependencies so parallel runs are safe; .serialized only as a stopgap
  • Tag tests to slice them in test plans and swift test --filter

Related concepts

  • XCTest assertions, parameterized tests, setup and teardown, test isolation, testing error paths, async testing patterns, XCTExpectFailure vs withKnownIssue, test discovery