skip to content

In Swift Testing, how does @Test(arguments:) turn a table of currency-conversion cases into test cases, and what changes with two collections or zip?

level: middleimportance: should knowfreq 55%

answer

  1. one call per element
  2. each call reported on its own
  3. two collections multiply
  4. zip pairs by position

basics

~20 s

@Test(arguments:) calls the function once per element, and each call is a separate test case reported with its arguments and run in parallel. Two collections produce every combination of their elements; zip pairs them by position instead.

solid answer

~40 s

With `@Test(arguments: ["USD", "EUR", "JPY"]) func roundTrip(code: String)`, Swift Testing calls the function once per element; each call is a **test case** that passes or fails on its own, shows its argument in the report, and runs in parallel with the others by default. Unlike a `for` loop inside one test, a failure names the input and the remaining inputs still report. Passing two collections, `arguments: codes, amounts`, runs the **Cartesian product**: 3 codes and 4 amounts give 12 cases. To pair a currency with its expected result instead, pass `zip(codes, expected)`, which gives one case per pair, destructured into the function's two parameters. `@Test` accepts at most two collections, so a richer table becomes one collection of a `Sendable` struct.

code

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

struct ParameterizedConversionTests {
    static let converter = CurrencyConverter(rates: [
        "USD": 1, "EUR": Decimal(92) / 100, "JPY": 150,
    ])

    @Test("Every supported currency round-trips", arguments: ["USD", "EUR", "JPY"])
    func roundTrip(code: String) throws {
        let there = try Self.converter.convert(100, from: "USD", to: code)
        let back = try Self.converter.convert(there, from: code, to: "USD")
        #expect(back == 100)
    }

    @Test(arguments: zip(["EUR", "JPY"], [Decimal(92), 15_000]))
    func hundredDollars(code: String, expected: Decimal) throws {
        #expect(try Self.converter.convert(100, from: "USD", to: code) == expected)
    }

    @Test(arguments: ["USD", "EUR"], ["EUR", "JPY"])
    func everyPairConverts(from: String, to: String) throws {
        _ = try Self.converter.convert(1, from: from, to: to)
    }
}

go deeper

for a junior

Recall that arguments: calls the test once per element and that each call is reported separately with its input.

for a middle

Explain the Cartesian product of two collections versus zip, the two-collection limit, and why arguments must be Sendable when cases run in parallel.

for a senior

Show judgment about case design: curated tables over combinatorial explosions, Encodable arguments so a failing case can be re-run, and no shared mutable state between parallel cases.

for a principal

Frame parameterized tables as the team's way to encode business rules, such as currency rounding, so product changes become one new row instead of a new test function.

## From a loop to test cases A **parameterized test** is a test function with parameters plus an `arguments:` list in its `@Test` attribute. Swift Testing calls the function once for each input, and each invocation is called a **test case**. Compare it with a loop inside one test: - With a `for` loop, the first failure is reported against the whole test, and you have to read the message to learn which currency broke. - With `@Test(arguments:)`, each case is reported with its arguments, such as `code → "JPY"`, and the other cases still pass or fail independently. - Cases of one test function **run in parallel** with each other by default, like separate tests do. The arguments must be a `Collection` that is `Sendable` with `Sendable` elements, because cases can run concurrently. Common sources are array literals, `CaseIterable.allCases` (so a newly added enum case is tested automatically), and integer ranges such as `1...100`. The arguments expression may use `try` and `await`; it is evaluated lazily, only when the test is actually going to run. ## The shapes of `arguments:` | You write | The function takes | Cases produced | |---|---|---| | `arguments: codes` | one parameter | one per element | | `arguments: codes, amounts` | two parameters | every combination, `codes.count × amounts.count` | | `arguments: zip(codes, expected)` | two parameters | one per pair, stopping at the shorter collection | | `arguments: [("EUR", 92), ("JPY", 15_000)]` | two parameters | one per tuple, destructured | | `arguments: [ConversionCase(…), …]` | one `Sendable` struct | one per element | Two separate collections are the **Cartesian product**: three currencies and four amounts make twelve cases. That is right when every combination is meaningful (every currency pair must convert) and wrong when each input has its own expected output; there, **`zip`** keeps the pairs aligned and the case count linear. `@Test` accepts **at most two collections**: writing three is a compile error. For a currency-conversion table with a source, a target, an amount and an expected result, model a row as a `Sendable` struct and pass an array of rows. ## How cases run 1. Swift Testing evaluates the arguments expression and builds one case per element or pair. 2. Cases run concurrently with each other and with other tests, unless the test or its suite has the `.serialized` trait, which makes the cases of that test run one at a time. 3. A time limit set with `.timeLimit` applies to **each case individually**, not to the whole parameterized test. 4. The report shows a summary such as "with 3 test cases passed" and, for failures, each failing case with its argument values. ## Re-running one failing case Swift Testing lets tools such as Xcode re-run selected cases of a parameterized test, which matters when one of a hundred inputs fails. That works only when every argument can be matched deterministically: Swift Testing checks each argument for `CustomTestArgumentEncodable`, a `RawRepresentable` type with an `Encodable` raw value, `Encodable`, or `Identifiable` with an `Encodable` ID, in that order. Strings, numbers and simple enums qualify; a class without any of these does not, and its cases can only be run all together. ## Pitfalls - **Combinatorial blow-up.** Two collections of 100 elements each make 10,000 cases; reach for `zip` or a curated table. - **Expecting order.** Cases run in parallel and in no promised order; a case must not depend on another case having run first. - **Sharing state through static properties.** A `static let` converter that is only read is fine; a `static var` mutated by cases is a data race. - **Very large ranges.** `0..<Int.max` may never finish. - **Computing the expected value with the code under test.** A table of literal expected results is what makes the cases meaningful. - **Tuples wider than two.** Only two-element tuples are destructured into two parameters; for three or more values per case, use a struct. ## Sharing argument lists When two tests need the same table, put it in a `static` property or function and pass it to each `@Test`, for example `@Test(arguments: ConversionCase.all)`. Because the expression is evaluated lazily, a slow source such as a fixture file loaded with `try` is read only for tests that actually run, and a filtered run that skips the test never pays for it.

  • How do you parameterize a Swift Testing test over four values per case when @Test accepts at most two collections?
    Define a `Sendable` struct such as `ConversionCase` with `from`, `to`, `amount` and `expected`, build an array of them and pass it as the single collection: `@Test(arguments: cases) func converts(_ c: ConversionCase)`. Making the struct `Encodable` or `Identifiable` with an `Encodable` ID also lets you re-run one failing case.
  • What does the .serialized trait change on a parameterized test?
    It makes that test's cases run one at a time instead of in parallel. It does not stop other tests from running alongside them, and on a test without arguments it has no effect, which the compiler reports as a warning.

  • Two argument collections are paired element by element.
  • zip runs every combination of the two collections.
  • A parameterized test stops at the first failing input, like a for loop.
  • You can pass one argument collection per function parameter, however many there are.
  • Parameterized cases always run in the order they are listed.