require(_:sourceLocation:performing:throws:)
Check that an expression always throws an error matching some condition, and throw an error if it does not.
Declaration
@discardableResult @freestanding(expression) macro require<R>(_ comment: @autoclosure () -> Comment? = nil, sourceLocation: SourceLocation = #_sourceLocation, performing expression: () async throws -> R, throws errorMatcher: (any Error) async throws -> Bool) -> any ErrorParameters
- 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
The error that was thrown by expression.
Overview
Use this overload of #require() 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 and an instance of ExpectationFailedError is thrown. Any value returned by expression is discarded.
If the thrown error need only be an instance of a particular type, use require(throws:_:sourceLocation:performing:) instead. If the thrown error need only equal another instance of Error, use require(throws:_:sourceLocation:performing:) instead.
If expression should never throw, simply invoke the code without using this macro. The test will then fail if an error is thrown.