Contents

Expectations and confirmations

Check for expected values, outcomes, and asynchronous events in tests.

Overview

Use expect(_:_:sourceLocation:) and require(_:_:sourceLocation:) 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 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 Testing asynchronous code.

Validate your code’s result

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:) 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:) throws an instance of ExpectationFailedError when your code fails to satisfy the requirement.

Topics

Checking expectations

Checking that errors are thrown

Checking how processes exit

Confirming that asynchronous events occur

Retrieving information about checked expectations

Representing source locations

See Also

Behavior validation