Swift Testing: @Test and #expect

suggest change

Swift Testing is the testing library that ships with Swift 6.0 and later (and Xcode 16). It replaces most uses of XCTest with a smaller API built on macros:

Swift Testing is open source and works on macOS, Linux and Windows. All examples below were run with Swift 6.4 on Windows, using swift test.

Creating a package with tests

swift package init creates a package with a test target that already uses Swift Testing (see Creation and usage of a simple Swift package for package basics):

mkdir Shop
cd Shop
swift package init --type library
Creating library package: Shop
Creating Package.swift
Creating .gitignore
Creating Sources
Creating Sources/Shop/Shop.swift
Creating Tests/
Creating Tests/ShopTests/
Creating Tests/ShopTests/ShopTests.swift

Package.swift has a .testTarget that depends on the library. You don't add Swift Testing as a dependency, because the toolchain includes it:

// swift-tools-version: 6.4
import PackageDescription

let package = Package(
    name: "Shop",
    products: [
        .library(name: "Shop", targets: ["Shop"]),
    ],
    targets: [
        .target(name: "Shop"),
        .testTarget(name: "ShopTests", dependencies: ["Shop"]),
    ]
)

The generated test file looks like this:

import Testing
@testable import Shop

@Test func example() async throws {
    // Write your test here and use APIs like `#expect(...)` to check expected conditions.
}

@testable import gives the tests access to internal declarations of the module.

Code under test

All tests in this article test this small shopping cart. Put it in Sources/Shop/Shop.swift. Prices are in cents, so the arithmetic is exact. The throws(CartError) syntax is typed throws:

public struct Item: Equatable, Sendable {
    public let name: String
    public let price: Int   // in cents
    public init(name: String, price: Int) {
        self.name = name
        self.price = price
    }
}

public enum CartError: Error, Equatable {
    case invalidQuantity(Int)
    case unknownCoupon(String)
}

public struct Cart {
    public private(set) var lines: [(item: Item, quantity: Int)] = []
    public private(set) var discountPercent = 0

    public init() {}

    public var isEmpty: Bool { lines.isEmpty }

    public var total: Int {
        let sum = lines.reduce(0) { $0 + $1.item.price * $1.quantity }
        return sum - sum * discountPercent / 100
    }

    public mutating func add(_ item: Item, quantity: Int = 1) throws(CartError) {
        guard quantity > 0 else { throw .invalidQuantity(quantity) }
        lines.append((item, quantity))
    }

    public mutating func apply(coupon: String) throws(CartError) {
        switch coupon {
        case "SAVE10": discountPercent = 10
        case "HALF": discountPercent = 50
        default: throw .unknownCoupon(coupon)
        }
    }

    public func firstLine(named name: String) -> (item: Item, quantity: Int)? {
        lines.first { $0.item.name == name }
    }
}

public func formatCents(_ cents: Int) -> String {
    let sign = cents < 0 ? "-" : ""
    let c = abs(cents)
    let frac = c % 100
    return "\(sign)$\(c / 100).\(frac < 10 ? "0" : "")\(frac)"
}

public func fetchPrice(of name: String) async throws -> Int {
    try await Task.sleep(for: .milliseconds(10))
    if name == "book" { return 1999 }
    throw CartError.unknownCoupon(name)
}

@Test and #expect

Replace Tests/ShopTests/ShopTests.swift with two tests:

import Testing
@testable import Shop

@Test func emptyCartHasZeroTotal() {
    let cart = Cart()
    #expect(cart.isEmpty)
    #expect(cart.total == 0)
}

@Test("Adding items sums their prices")
func addingItems() throws {
    var cart = Cart()
    try cart.add(Item(name: "pen", price: 150), quantity: 2)
    try cart.add(Item(name: "book", price: 1999))
    #expect(cart.total == 2299)
}

A test is any function marked with @Test. It can be throws and async. If it throws an error that nobody catches, the test fails with that error, so you can write try without a do/catch.

The string in @Test("...") is a display name used in reports instead of the function name.

Run the tests with swift test:

$ swift test
Building for debugging...
Build complete! (38.73 secs)
...
◊ Test run started.
→ Testing Library Version: 6.4.1 (804dc4530ef3666)
→ Target Platform: x86_64-unknown-windows-msvc
◊ Test "Adding items sums their prices" started.
◊ Test emptyCartHasZeroTotal() started.
√ Test emptyCartHasZeroTotal() passed after 0.001 seconds.
√ Test "Adding items sums their prices" passed after 0.001 seconds.
√ Test run with 2 tests in 0 suites passed after 0.001 seconds.

swift test runs XCTest tests too, so before the Swift Testing output you also see an XCTest summary saying "Executed 0 tests". Pass --disable-xctest to skip it. The symbols differ by platform: macOS terminals show ✔ and ✘ where Windows shows √ and ×.

Swift Testing runs tests in parallel by default, and in a random order. That's why emptyCartHasZeroTotal() started second but finished first. Tests must not depend on each other or on shared mutable state.

What a failure looks like

#expect is a macro, so it sees the expression itself, not only its result. When the check fails, it reports the value of each part of the expression:

@Test func totalWithCoupon() throws {
    var cart = Cart()
    try cart.add(Item(name: "pen", price: 150), quantity: 2)
    try cart.apply(coupon: "SAVE10")
    let expected = 280
    #expect(cart.total == expected)
    #expect(cart.lines.count == 2)
    #expect(formatCents(cart.total).hasPrefix("$3"))
}
◊ Test totalWithCoupon() started.
× Test totalWithCoupon() recorded an issue at ShopTests.swift:9:5: Expectation failed: cart.total == expected
→ cart.total == expected → false
→   cart.total → 270
→   expected → 280
× Test totalWithCoupon() recorded an issue at ShopTests.swift:10:5: Expectation failed: cart.lines.count == 2
→ cart.lines.count == 2 → false
→   cart.lines.count → 1
× Test totalWithCoupon() recorded an issue at ShopTests.swift:11:5: Expectation failed: formatCents(cart.total).hasPrefix("$3")
→ formatCents(cart.total).hasPrefix("$3") → false
→   formatCents(cart.total) → "$2.70"
× Test totalWithCoupon() failed after 0.001 seconds with 3 issues.
× Test run with 1 test in 0 suites failed after 0.002 seconds with 3 issues.

A failed #expect records an issue and the test keeps running, so you see every failed expectation in one run. Here all three fail: the first two expectations are wrong, and the third is just a consequence.

You don't need special assertions for comparisons. Use ==, <, !, contains, hasPrefix or any other Boolean expression.

You can add a comment as a second argument. It's printed when the expectation fails:

@Test func discountMessage() throws {
    var cart = Cart()
    try cart.add(Item(name: "pen", price: 150), quantity: 2)
    try cart.apply(coupon: "SAVE10")
    #expect(cart.total == 280, "SAVE10 should take 10% off \(formatCents(300))")
}
× Test discountMessage() recorded an issue at ShopTests.swift:9:5: Expectation failed: cart.total == 280
→ SAVE10 should take 10% off $3.00
→ cart.total == 280 → false
→   cart.total → 270

#require: stop the test early

Sometimes there's no point in continuing after a failed check. #require works like #expect, but it throws when the check fails, which ends the test. You call it with try.

Its most common use is unwrapping an optional. try #require(optional) returns the unwrapped value or fails the test. It replaces XCTUnwrap:

@Test func firstLineQuantity() throws {
    var cart = Cart()
    try cart.add(Item(name: "pen", price: 150), quantity: 3)
    let line = try #require(cart.firstLine(named: "pencil"))
    #expect(line.quantity == 3)
}
× Test firstLineQuantity() recorded an issue at ShopTests.swift:7:20: Expectation failed: cart.firstLine(named: "pencil")
→ cart.firstLine(named: "pencil") → nil
→   cart → Cart(lines: [(item: Shop.Item(name: "pen", price: 150), quantity: 3)], discountPercent: 0)
→     lines → [(item: Shop.Item(name: "pen", price: 150), quantity: 3)]
→     discountPercent → 0
× Test firstLineQuantity() failed after 0.003 seconds with 1 issue.

The test ends at #require, so the #expect after it never runs. #require also accepts a Boolean, like try #require(!cart.isEmpty).

A good rule: use #expect by default, and #require when later lines can't run without the value.

Testing errors with #expect(throws:)

#expect(throws:) takes a closure and checks that it throws. You can check for an error type, a specific Equatable error value, or that nothing is thrown:

@Test func rejectsZeroQuantity() {
    var cart = Cart()
    // any error of type CartError
    #expect(throws: CartError.self) {
        try cart.add(Item(name: "pen", price: 150), quantity: 0)
    }
    // exactly this error value
    #expect(throws: CartError.invalidQuantity(-1)) {
        try cart.add(Item(name: "pen", price: 150), quantity: -1)
    }
    // the macro returns the error, so you can inspect it
    let error = #expect(throws: CartError.self) {
        try cart.apply(coupon: "FREE")
    }
    #expect(error == .unknownCoupon("FREE"))
    // must not throw
    #expect(throws: Never.self) {
        try cart.apply(coupon: "HALF")
    }
}

Since Swift 6.1, #expect(throws:) returns the caught error (or nil if the check failed), which is simpler than the older #expect { ... } throws: { error in ... } form.

If the closure doesn't throw, the test fails:

@Test func wrongError() {
    var cart = Cart()
    #expect(throws: CartError.unknownCoupon("X")) {
        try cart.apply(coupon: "SAVE10")
    }
}
× Test wrongError() recorded an issue at ShopTests.swift:36:5: Expectation failed: an error was expected but none was thrown
× Test wrongError() failed after 0.001 seconds with 1 issue.

#require(throws:) also exists. It throws (ending the test) when the expected error isn't thrown.

Async tests

Mark the test async and use await as in any other async function. For an async closure, put await in front of #expect(throws:):

@Test func fetchesPrice() async throws {
    let price = try await fetchPrice(of: "book")
    #expect(price == 1999)
    await #expect(throws: CartError.self) {
        try await fetchPrice(of: "unicorn")
    }
}

To check that a callback was called, use confirmation. It fails the test if confirm() (here named added) isn't called the expected number of times before the closure returns:

struct Logger {
    let onRecord: (String) -> Void
    mutating func record(_ s: String) { onRecord(s) }
}

@Test func callbackFiresTwice() async {
    await confirmation("item added", expectedCount: 2) { added in
        var log = Logger { _ in added() }
        log.record("pen")
        log.record("book")
    }
}

confirmation replaces XCTestExpectation. Unlike wait(for:timeout:), it doesn't wait. The events must happen before the closure returns, so await the async work inside it.

Grouping tests with @Suite

A type that contains @Test methods is a suite. The @Suite attribute is optional, but you need it to give the suite a display name or traits:

@Suite("Cart")
struct CartTests {
    var cart = Cart()
    let pen = Item(name: "pen", price: 150)

    init() throws {
        print("init: fresh cart")
        try cart.add(pen, quantity: 2)
    }

    @Test mutating func addsMore() throws {
        try cart.add(pen)
        #expect(cart.total == 450)
    }

    @Test func startsWithTwoPens() {
        #expect(cart.total == 300)
    }

    @Suite struct Coupons {
        @Test func save10() throws {
            var cart = Cart()
            try cart.add(Item(name: "book", price: 2000))
            try cart.apply(coupon: "SAVE10")
            #expect(cart.total == 1800)
        }
    }
}
◊ Suite "Cart" started.
◊ Suite Coupons started.
◊ Test addsMore() started.
◊ Test startsWithTwoPens() started.
◊ Test save10() started.
√ Test addsMore() passed after 0.001 seconds.
√ Test save10() passed after 0.001 seconds.
√ Test startsWithTwoPens() passed after 0.001 seconds.
√ Suite Coupons passed after 0.001 seconds.
√ Suite "Cart" passed after 0.001 seconds.
√ Test run with 3 tests in 2 suites passed after 0.001 seconds.
init: fresh cart
init: fresh cart

Swift Testing creates a new instance of the suite for every test. That's why init ran twice, and why startsWithTwoPens() still sees a total of 300 even though addsMore() added a third pen to its own copy. init takes the place of XCTest's setUp(). For cleanup, make the suite a class or actor and use deinit in place of tearDown().

Suites can be structs, classes, enums or actors. Structs are the usual choice because value semantics keep tests isolated. A test method can be mutating.

Parameterized tests

Pass a collection to arguments: and the function runs once for each element. Each run is a separate test case, and the cases run in parallel:

@Test(arguments: [0, 5, 99, 100, 1999, -250])
func formatsCents(cents: Int) {
    let s = formatCents(cents)
    #expect(s.contains("."))
    #expect(!s.hasSuffix(".5"))
}

For input/output pairs, pass tuples:

@Test(arguments: [
    (0, "$0.00"),
    (5, "$0.05"),
    (1999, "$19.99"),
    (-250, "-$2.50"),
    (100, "$1.0"),
])
func formatting(cents: Int, expected: String) {
    #expect(formatCents(cents) == expected)
}

The last pair has a typo. The failure report names the arguments of the failing case (the "test case started" lines are trimmed):

× Test formatting(cents:expected:) recorded an issue with 2 arguments cents → 100, expected → "$1.0" at ShopTests.swift:19:5: Expectation failed: formatCents(cents) == expected
→ formatCents(cents) == expected → false
→   formatCents(cents) → "$1.00"
→   expected → "$1.0"
× Test formatting(cents:expected:) with 5 test cases failed after 0.003 seconds with 1 issue.

This beats a for loop inside one test: each case is reported on its own, the others still run, and in Xcode you can re-run a single failing case.

With two collections, the test runs for every combination (2 x 2 = 4 cases here):

@Test(arguments: ["SAVE10", "HALF"], [1000, 333])
func couponsNeverIncreaseTotal(coupon: String, price: Int) throws {
    var cart = Cart()
    try cart.add(Item(name: "x", price: price))
    try cart.apply(coupon: coupon)
    #expect(cart.total < price)
}

To pair the elements up instead, use zip:

@Test(arguments: zip(["SAVE10", "HALF"], [900, 500]))
func couponTotals(coupon: String, expected: Int) throws {
    var cart = Cart()
    try cart.add(Item(name: "x", price: 1000))
    try cart.apply(coupon: coupon)
    #expect(cart.total == expected)
}
√ Test couponTotals(coupon:expected:) with 2 test cases passed after 0.002 seconds.
√ Test couponsNeverIncreaseTotal(coupon:price:) with 4 test cases passed after 0.002 seconds.

Arguments must be Sendable. Ranges (1...3) and enums that conform to CaseIterable (arguments: Size.allCases) work too.

Traits

Traits are extra arguments to @Test or @Suite that change how tests run. A trait on a suite applies to every test in it.

extension Tag {
    @Tag static var pricing: Self
    @Tag static var network: Self
}

let runSlowTests = false

@Test(.tags(.pricing))
func halfPrice() throws {
    var cart = Cart()
    try cart.add(Item(name: "book", price: 2000))
    try cart.apply(coupon: "HALF")
    #expect(cart.total == 1000)
}

@Test("Price lookup", .tags(.network, .pricing), .timeLimit(.minutes(1)))
func priceLookup() async throws {
    #expect(try await fetchPrice(of: "book") == 1999)
}

@Test(.disabled("Coupons stack in v2"))
func stackedCoupons() {
    Issue.record("should not run")
}

@Test(.enabled(if: runSlowTests, "set runSlowTests to run"))
func slowTest() {}

@Test(.bug("https://example.com/issues/42", "rounding"))
func roundsDown() throws {
    var cart = Cart()
    try cart.add(Item(name: "x", price: 333))
    try cart.apply(coupon: "SAVE10")
    // should round in the customer's favor: 299, not 300
    withKnownIssue("discount rounds toward zero") {
        #expect(cart.total == 299)
    }
}

@Suite(.serialized)
struct Ordered {
    @Test(arguments: 1...3) func step(n: Int) { print("step", n) }
}
◊ Suite Ordered started.
➜ Test stackedCoupons() skipped: "Coupons stack in v2"
➜ Test slowTest() skipped: "set runSlowTests to run"
◊ Test "Price lookup" started.
◊ Test halfPrice() started.
◊ Test roundsDown() started.
◊ Test step(n:) started.
◊ Test case passing 1 argument n → 1 to step(n:) started.
√ Test halfPrice() passed after 0.001 seconds.
◊ Test case passing 1 argument n → 2 to step(n:) started.
- Test roundsDown() recorded a known issue at ShopTests.swift:38:9: Expectation failed: cart.total == 299
→ discount rounds toward zero
→ cart.total == 299 → false
→   cart.total → 300
◊ Test case passing 1 argument n → 3 to step(n:) started.
- Test roundsDown() passed after 0.001 seconds with 1 known issue.
√ Test step(n:) with 3 test cases passed after 0.001 seconds.
√ Suite Ordered passed after 0.001 seconds.
√ Test "Price lookup" passed after 0.019 seconds.
- Test run with 6 tests in 1 suite passed after 0.020 seconds with 1 known issue.
step 1
step 2
step 3

The traits used here:

withKnownIssue { } is not a trait, but it's often used with .bug. Failures inside it are recorded as known issues and don't fail the test. Once the bug is fixed, the code no longer fails, and withKnownIssue reports that as an issue ("Known issue was not recorded"), which reminds you to remove it.

Issue.record("message") fails the test unconditionally, like XCTFail.

Running a subset of tests

swift test list prints the test identifiers:

$ swift test list
ShopTests.Ordered/step(n:)
ShopTests.halfPrice()
ShopTests.priceLookup()
ShopTests.roundsDown()
ShopTests.slowTest()
ShopTests.stackedCoupons()

--filter runs only tests whose identifier matches a regular expression, and --skip excludes tests:

$ swift test --disable-xctest --filter priceLookup
◊ Test run started.
→ Testing Library Version: 6.4.1 (804dc4530ef3666)
→ Target Platform: x86_64-unknown-windows-msvc
◊ Test "Price lookup" started.
√ Test "Price lookup" passed after 0.025 seconds.
√ Test run with 1 test in 0 suites passed after 0.026 seconds.
swift test --skip Ordered                # everything except the Ordered suite
swift test --filter "ShopTests.Ordered"  # only one suite

swift test returns a non-zero exit code when any test fails, so it works as is in CI scripts.

Comparison with XCTest

XCTest still works, and both libraries can be used in the same test target, even in the same file. swift test runs both. Here is an XCTest test of the same cart:

import XCTest
@testable import Shop

final class CartXCTests: XCTestCase {
    func testTotal() throws {
        var cart = Cart()
        try cart.add(Item(name: "pen", price: 150), quantity: 2)
        XCTAssertEqual(cart.total, 300)
        XCTAssertThrowsError(try cart.apply(coupon: "NOPE"))
    }
}
XCTest Swift Testing
class FooTests: XCTestCase struct FooTests (optionally @Suite), or free functions
func testSomething() @Test func something()
XCTAssertEqual(a, b), XCTAssertTrue(x), XCTAssertNil(x) ... #expect(a == b), #expect(x), #expect(x == nil)
try XCTUnwrap(x) try #require(x)
XCTAssertThrowsError(try f()) #expect(throws: (any Error).self) { try f() }
XCTFail("msg") Issue.record("msg")
setUp() / tearDown() init / deinit
XCTestExpectation + wait(for:) confirmation { } or plain await
XCTSkip, renaming the method .disabled, .enabled(if:)
loop inside one test @Test(arguments:)
parallel across processes, opt-in parallel in-process by default

What stays with XCTest for now: UI tests (XCUIApplication) and performance tests (measure { }). Don't mix the two APIs inside one test. In older toolchains a failing XCTAssert... inside a @Test function was silently ignored. Recent ones (Swift 6.4 here) record it as a failure, plus a warning that suggests the Swift Testing equivalent:

× Test xctInside() recorded an issue at ShopTests.swift:11:1: Issue recorded
▲ Test xctInside() recorded a warning at ShopTests.swift:11:1: An API was misused
→ Replace XCTest API such as 'XCTAssert' with a Swift Testing equivalent such as '#expect'.

To learn about testing code that depends on other components, see Leveraging Protocol Oriented Programming for Unit Testing. Its approach of hiding dependencies behind protocols works the same way with Swift Testing.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents