expect(_:sourceLocation:performing:throws:)
Check that an expression always throws an error matching some condition.
Declaration
@discardableResult @freestanding(expression) macro expect<R>(_ comment: @autoclosure () -> Comment? = nil, sourceLocation: SourceLocation = #_sourceLocation, performing expression: () async throws -> R, throws errorMatcher: (any Error) async throws -> Bool) -> (any Error)?Parameters
- comment:
A comment describing the expectation.
- sourceLocation:
The source location to which recorded expectations and issues should be attributed.
- expression:
The expression to be evaluated.
- errorMatcher:
A closure to invoke when
expressionthrows an error that indicates if it matched or not.
Return Value
If the expectation passes, the error that was thrown by expression. If the expectation fails, the result is nil.
Overview
Use this overload of #expect() when the expression expression should throw an error, but the logic to determine if the error matches is complex:
#expect {
FoodTruck.shared.engine.batteryLevel = 0
try FoodTruck.shared.engine.start()
} throws: { error in
return error == EngineFailureError.batteryDied
|| error == EngineFailureError.stillCharging
}If expression does not throw an error, if it throws an error that is not matched by errorMatcher, or if errorMatcher throws an error (including the error passed to it), an Issue is recorded for the test that is running in the current task. Any value returned by expression is discarded.
If the thrown error need only be an instance of a particular type, use expect(throws:_:sourceLocation:performing:) instead. If the thrown error need only equal another instance of Error, use expect(throws:_:sourceLocation:performing:) instead.