In Swift Testing, when should a test use #require instead of #expect, and how does #expect(throws:) check for a specific error?
answer
- record and continue, or record and stop
- needs try and a throwing test
- unwraps an optional for later lines
- error type or equal error value
basics
~20 s#expect records a failure and lets the test continue; try #require records it, then throws to end the test, and unwraps optionals. #expect(throws:) given an error type or an equal error value passes only when its closure throws a match.
solid answer
~40 sUse `#expect` for independent checks you want reported together, and `try #require` when the rest of the test depends on the condition. `#require` records the issue and then throws an `ExpectationFailedError`, so it needs `try` inside a throwing test, and its optional form returns the unwrapped value: `let rate = try #require(converter.rate(for: "EUR"))`. For errors, `#expect(throws: ConversionError.self) { … }` passes if the closure throws that type, `#expect(throws: ConversionError.unknownCurrency("XYZ")) { … }` requires an equal value, so the error must be `Equatable`, and `#expect(throws: Never.self)` asserts nothing is thrown. Since Swift 6.1 both `#expect(throws:)` and `#require(throws:)` return the caught error, so you can inspect its payload with further expectations.
code
swift · 25 linesimport Foundation
import Testing
@testable import Exchange
struct ConversionErrorTests {
let converter = CurrencyConverter(rates: ["USD": 1, "EUR": Decimal(92) / 100])
@Test func eurRateIsPositive() throws {
let rate = try #require(converter.rate(for: "EUR")) // stops here if nil
#expect(rate > 0)
}
@Test func unknownCurrencyIsRejected() {
#expect(throws: ConversionError.unknownCurrency("XYZ")) {
try converter.convert(10, from: "USD", to: "XYZ")
}
}
@Test func negativeAmountIsAConversionError() {
let error = #expect(throws: ConversionError.self) {
try converter.convert(-1, from: "USD", to: "EUR")
}
#expect(error == .negativeAmount)
}
}go deeper
Recall the one-line rule: #expect records and continues, try #require records and stops, and #require on an optional hands back the unwrapped value.
Explain the mechanics: #require throws ExpectationFailedError, so the test must be throwing; the throws: forms differ by type, Equatable value and Never; since Swift 6.1 they return the error.
Show where each choice changes a failing report: cascades of nil failures without #require, lost information with too many #require calls, and known bugs that belong in withKnownIssue rather than an expected error.
Set a team convention for error tests, such as exact-case checks for public error contracts and type checks plus payload inspection elsewhere, so tests pin behaviour without over-specifying it.
## Two macros, two failure modes Swift Testing has two checking macros, and the difference is what happens **after** a failure: | | `#expect` | `#require` | |---|---|---| | On failure | records an issue | records an issue, then throws `ExpectationFailedError` | | Test continues? | yes | no, the throw ends the test | | Call syntax | `#expect(x == y)` | `try #require(x == y)` | | Test must be `throws`? | no | yes | | Optional form | none | `try #require(optional)` returns the unwrapped value | Both record the same rich failure message with captured values. Neither crashes the process: a thrown `ExpectationFailedError` is an ordinary Swift error that ends one test function, and every other test keeps running. ## #require as a precondition and an unwrapper Reach for **`#require`** when later lines are meaningless if a condition fails: - **Unwrapping optionals.** `let rate = try #require(converter.rate(for: "EUR"))` gives a non-optional `Decimal` for the rest of the test. If the method returns `nil`, the test records `Expectation failed: converter.rate(for: "EUR")` with the captured `nil` and stops, instead of producing a cascade of follow-on failures or forcing `!`. - **Preconditions.** `try #require(items.count == 3)` before indexing `items[2]` keeps a failed setup from turning into an out-of-range trap that would take down the process. Reach for **`#expect`** for everything else. A conversion test that checks the amount, the currency code and the rounding with three `#expect` calls reports all three problems in one run, where three `#require` calls would show only the first. ## Checking thrown errors The `throws:` forms take a closure and check what it throws: 1. **`#expect(throws: ConversionError.self) { try … }`** passes if the closure throws any `ConversionError`. 2. **`#expect(throws: ConversionError.unknownCurrency("XYZ")) { try … }`** passes only if the thrown error is **equal** to that value. This overload requires the error type to conform to both `Error` and `Equatable`. 3. **`#expect(throws: (any Error).self) { try … }`** passes for any thrown error. 4. **`#expect(throws: Never.self) { try … }`** asserts that the closure throws **nothing**. If the closure throws nothing (in forms 1 to 3), or throws an error that does not match, an issue is recorded. `#require(throws:)` has the same forms and, like `#require`, throws to end the test when the check fails. ## Inspecting the returned error Since **Swift 6.1**, both macros **return the caught error**. `#expect(throws: ConversionError.self)` returns `ConversionError?` (nil when the expectation failed) and `#require(throws:)` returns it non-optional. That makes payload checks plain: ```swift let error = try #require(throws: ConversionError.self) { try converter.convert(10, from: "USD", to: "XYZ") } #expect(error == .unknownCurrency("XYZ")) ``` The older style passed a matcher closure (`#expect { … } throws: { error in … }`); the documentation now recommends examining the returned error instead. With a compiler older than 6.1, the `throws:` macros return nothing. ## Choosing quickly - Independent facts about one result: several `#expect`. - A value later lines depend on: `try #require`. - "Must throw this exact case": the value form, with an `Equatable` error. - "Must throw something of this type, then check details": the type form plus the returned error. - "Must not throw": `#expect(throws: Never.self)`, or simply `try` the call in a throwing test, because an error escaping a test function is recorded as a failure too. - A failure you already know about and cannot fix yet: wrap it in `withKnownIssue` rather than turning the bug into an expected error, so reports show it as a known issue. ## Pitfalls - Writing `#require` without `try`: the compiler rejects it, and the fix is to mark the test `throws`, not to switch to `#expect` blindly. - Expecting `#expect(throws: SomeError.self)` to accept any error: an error of a different type is a failure. - Using the value form with a non-`Equatable` error: it does not compile; use the type form and inspect the result. - Putting several statements in a `throws:` closure: the check passes if **any** of them throws the error, so a setup line that throws the same error can make the test pass for the wrong reason. Keep only the call under test inside the closure. - Catching the error yourself with `do`/`catch` and calling `Issue.record` in the `catch`: it works, but it is longer than the macro and loses the expectation-specific failure message. A useful habit when reviewing tests: read every `try #require` and ask whether later lines truly depend on it. If they do not, it should be `#expect`, so one run reports every broken fact about the result.
- Why does #expect(throws: ConversionError.unknownCurrency("XYZ")) only compile when ConversionError is Equatable?That overload compares the thrown error with the expected value using `==`, so it is constrained to `Error & Equatable`. For an error type you cannot make `Equatable`, use the type form `#expect(throws: ConversionError.self)` and, since Swift 6.1, inspect the returned error with a `switch` or further `#expect` calls.
- How do you assert that a call does not throw in Swift Testing?`#expect(throws: Never.self) { try converter.convert(1, from: "USD", to: "EUR") }` records an issue if anything is thrown and lets the test continue. In a throwing test you can also just write `try` before the call: an error escaping the test function is recorded as a failure, but it ends the test at that point.
- #require is just #expect under a different name.
- After #require fails, the remaining expectations in the test still run.
- A failed #require crashes the process like a force unwrap.
- #expect(throws: ConversionError.self) passes for any thrown error.
- You must wrap a throwing call in do-catch to test which error it throws.
Assumes Swift Testing in Swift 6.4; #expect(throws:) and #require(throws:) return the caught error since Swift 6.1, and return nothing with older compilers.