Check for expected values, outcomes, and asynchronous events in tests.
Use expect(_:_:sourceLocation:)
and
require(_:_:sourceLocation:)-5l63q
macros to validate expected
outcomes. To validate that an error is thrown, or not thrown, the
testing library provides several overloads of the macros that you can
use. For more information, see doc:testing-for-errors-in-swift-code.
Use a Confirmation
to confirm the occurrence of an
asynchronous event that you can't check directly using an expectation.
For more information, see doc:testing-asynchronous-code.
To validate that your code produces an expected value, use
expect(_:_:sourceLocation:)
. This macro captures the
expression you pass, and provides detailed information when the code doesn't
satisfy the expectation.
@Test func calculatingOrderTotal() {
let calculator = OrderCalculator()
#expect(calculator.total(of: [3, 3]) == 7)
// Prints "Expectation failed: (calculator.total(of: [3, 3]) → 6) == 7"
}
Your test keeps running after expect(_:_:sourceLocation:)
fails. To stop
the test when the code doesn't satisfy a requirement, use
require(_:_:sourceLocation:)-5l63q
instead:
@Test func returningCustomerRemembersUsualOrder() throws {
let customer = try #require(Customer(id: 123))
// The test runner doesn't reach this line if the customer is nil.
#expect(customer.usualOrder.countOfItems == 2)
}
require(_:_:sourceLocation:)-5l63q
throws an instance of
ExpectationFailedError
when your code fails to satisfy the requirement.
expect(_:_:sourceLocation:)
require(_:_:sourceLocation:)-5l63q
require(_:_:sourceLocation:)-6w9oo
- doc:testing-for-errors-in-swift-code
expect(throws:_:sourceLocation:performing:)-79piu
expect(throws:_:sourceLocation:performing:)-1xr34
expect(_:sourceLocation:performing:throws:)
require(throws:_:sourceLocation:performing:)-76bjn
require(throws:_:sourceLocation:performing:)-7v83e
require(_:sourceLocation:performing:throws:)
- doc:testing-asynchronous-code
confirmation(_:expectedCount:isolation:sourceLocation:_:)-5mqz2
confirmation(_:expectedCount:isolation:sourceLocation:_:)-l3il
Confirmation
Expectation
ExpectationFailedError
CustomTestStringConvertible
SourceLocation