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]) == 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:)-5l63qrequire(_:_:sourceLocation:)-6w9oo
- doc:testing-for-errors-in-swift-code
expect(throws:_:sourceLocation:performing:)-1hfmsexpect(throws:_:sourceLocation:performing:)-7du1hexpect(_:sourceLocation:performing:throws:)require(throws:_:sourceLocation:performing:)-7n34rrequire(throws:_:sourceLocation:performing:)-4djuwrequire(_:sourceLocation:performing:throws:)
- doc:exit-testing
expect(processExitsWith:observing:_:sourceLocation:performing:)require(processExitsWith:observing:_:sourceLocation:performing:)ExitStatusExitTest
- doc:testing-asynchronous-code
confirmation(_:expectedCount:isolation:sourceLocation:_:)-5mqz2confirmation(_:expectedCount:isolation:sourceLocation:_:)-l3ilConfirmation
ExpectationExpectationFailedError
SourceLocation