skip to content

In Swift Testing, how do you declare a test with @Test, check a result with #expect, and add a display name and traits?

level: juniorimportance: must knowfreq 75%

answer

  1. an attribute, not a naming rule
  2. one macro, ordinary Swift operators
  3. records the failure, keeps going
  4. name string first, then traits

basics

~20 s

Mark any function with @Test and check results with #expect(condition), which records a failure with the captured values and lets the test continue. @Test also takes an optional display-name string followed by traits such as .tags, .disabled or .enabled(if:).

solid answer

~50 s

In Swift Testing a test is any function marked `@Test`: a global function, a static method or an instance method of a suite type, with no required name prefix and no base class, and it may be `async`, `throws` or `@MainActor`. Inside it you write `#expect(result == 92)`. The macro takes ordinary Swift expressions, so `==`, `<`, `!` and `!= nil` replace a family of assertion functions; on failure it records an issue that shows the captured values of the subexpressions, then lets the test continue. `@Test("USD to EUR uses the EUR rate")` sets the display name shown in Xcode and the console. Traits follow the name: `.tags(.currency)` groups tests for filtering, `.disabled("reason")` skips with a reason, `.enabled(if:)` decides at run time, `.bug(...)` links a tracker entry and `.timeLimit(.minutes(1))` caps the run time. Traits on a `@Suite` are inherited by its tests.

code

swift · 27 lines
swift
import Foundation
import Testing
@testable import Exchange

extension Tag {
    @Tag static var currency: Self
}

@Suite("Currency conversion", .tags(.currency))
struct CurrencyConverterTests {
    let converter = CurrencyConverter(rates: ["USD": 1, "EUR": Decimal(92) / 100])

    @Test("Converting a currency to itself keeps the amount")
    func sameCurrency() throws {
        let result = try converter.convert(100, from: "USD", to: "USD")
        #expect(result == 100)
    }

    @Test("USD to EUR uses the EUR rate")
    func usdToEur() throws {
        let result = try converter.convert(100, from: "USD", to: "EUR")
        #expect(result == 92)
    }

    @Test(.disabled("Rounding rules not agreed yet"))
    func roundsToCents() {}
}

go deeper

for a junior

Recall that @Test marks the function, #expect takes an ordinary Swift condition, and the display name string comes before any traits. Be able to write a two-check test from memory.

for a middle

Explain why #expect can print captured operand values and why it continues after a failure. Know that each instance-method test gets a fresh suite instance and that suite traits are inherited.

for a senior

Show judgment about traits: .disabled with a reason instead of deleted tests, .enabled(if:) for environment-dependent tests, .bug links in reports, and a team tag vocabulary that makes filtered runs useful in CI.

for a principal

Frame the declaration style as a team convention: required display names, an agreed tag set and rules for when skipping is allowed, so reports stay readable as the test count grows.

## Declaring a test Swift Testing is the macro-based test library that ships with the Swift 6 toolchain and Xcode 16 and later. You import the `Testing` module and mark a function with the **`@Test`** attribute. That attribute, not the function's name, is what makes it a test: - The function can be **global**, **`static`**, or an **instance method** of a type. - It can be `async`, `throws`, or both, and it can be isolated to a global actor such as `@MainActor`. - Its name is free: `sameCurrency()` is as good as anything starting with `test`. - Swift Testing runs test functions on an arbitrary task, not on the main actor, unless you isolate them yourself. When a test is an instance method, Swift Testing creates a **fresh instance of the containing type for every test function** and calls the method on it, so stored properties such as `converter` in the example are set up again for each test. The type needs an initializer that takes no arguments; it may be implicit, `async` or `throws`. ## Checking results with #expect **`#expect`** is a freestanding macro that takes a Boolean expression. Because a macro sees the expression's source at compile time, one macro covers what used to be a family of assertion functions: | What you check | With `#expect` | |---|---| | equality | `#expect(result == 92)` | | ordering | `#expect(total > 0)` | | nil | `#expect(cache.rate(for: "GBP") == nil)` | | a Boolean | `#expect(!rates.isEmpty)` | | identity | `#expect(a === b)` | When the condition is false, `#expect` **records an issue** that fails the test and prints the expression together with the values it captured, such as `result → 92`. Then the test **keeps running**, so several independent checks in one test all report. When a later line cannot make sense after a failure (an optional that turned out `nil`, say), the companion macro `#require` is the tool: it records the issue and throws, ending the test. ## Display names `@Test` takes an optional **display name** as its first, unlabeled argument: `@Test("USD to EUR uses the EUR rate")`. Xcode's test navigator, the test report and the `swift test` console show that string instead of the function name. Without one, the function's signature (`usdToEur()`) is shown. A display name costs nothing and turns a test report into a readable specification of the currency module. ## Traits Everything else about a test is configured with **traits**, passed after the display name in the same attribute: - **`.tags(.currency)`** attaches tags, declared once as `extension Tag { @Tag static var currency: Self }`, so you can filter and group runs in Xcode or on the command line. - **`.disabled("Rounding rules not agreed yet")`** skips the test and reports it as skipped with that reason, instead of commenting it out. - **`.enabled(if: condition)`** evaluates a condition at run time, just before the test would start, and skips it when the condition is false. A good fit is a test that needs a staging server or an environment variable. - **`.bug("https://…", "title")`** or **`.bug(id: 4821)`** links the test to a tracker entry so a report says why it is special. - **`.timeLimit(.minutes(1))`** fails a test that runs too long; the limit is expressed in whole minutes. - **`.serialized`** controls parallel execution and is covered with parallel tests. Traits combine: `@Test("Live rates", .enabled(if: hasStaging), .tags(.currency), .timeLimit(.minutes(1)))`. ## Grouping with @Suite A type that contains test functions is a **suite** even without an attribute. Adding **`@Suite`** lets you give the group a display name and traits, and **traits on a suite are inherited by every test inside it**: tagging the suite `.tags(.currency)` tags all its tests, and `.disabled` on the suite skips them all. Suites can nest. A `struct` or an `actor` is the usual choice; the documentation recommends them over classes because they let the compiler better enforce concurrency safety. ## Mistakes interviewers listen for 1. Naming a function `testSomething` and forgetting `@Test`: without the attribute it is not discovered at all. 2. Expecting `#expect` to stop the test at the first failure; it records the issue and carries on. 3. Commenting a test out instead of using `.disabled("reason")`, which keeps it visible as skipped in every report. 4. Writing a different assertion function per comparison when one `#expect` with an ordinary operator does it and prints the operands for free.

  • What does #expect print when it fails, and why can it show more than a plain Boolean assertion function?
    It records `Expectation failed: result == 90` and expands the captured subexpressions, for example `result → 92`. `#expect` is a macro, so at compile time it sees the expression's structure and can capture each operand. A plain function only ever receives `false`, which is why older assertion styles needed a separate function per comparison to print both sides.
  • Does a test have to live inside a @Suite type?
    No. A global function marked `@Test` is discovered on its own, and any type containing `@Test` functions is already a suite. `@Suite` adds a display name and traits that its tests inherit. If the tests are instance methods, the type needs a zero-argument initializer, because Swift Testing creates a fresh instance for each test.
  • When should a Swift Testing test function be marked @MainActor?
    When the code under test is isolated to the main actor, such as a view model annotated `@MainActor`. Swift Testing runs test functions on an arbitrary task by default, so a test that touches main-actor state must be isolated itself, either with `@MainActor` on the function or by awaiting into the main actor for that part.

  • A Swift Testing function is discovered because its name starts with test.
  • #expect stops the test function at the first failing check.
  • You need a different assertion function for equality, nil and comparisons.
  • Every Swift Testing test must live in a class that inherits a test base class.
  • Commenting out a test is the same as marking it .disabled.