Using the other answers here, I wrote a helper function that works as a drop-in replacement for XCTAssertThrowsError
when working with async
functions.
import XCTest
/// Asserts that an asynchronous expression throws an error.
/// (Intended to function as a drop-in asynchronous version of `XCTAssertThrowsError`.)
///
/// Example usage:
///
/// await assertThrowsAsyncError(
/// try await sut.function()
/// ) { error in
/// XCTAssertEqual(error as? MyError, MyError.specificError)
/// }
///
/// - Parameters:
/// - expression: An asynchronous expression that can throw an error.
/// - message: An optional description of a failure.
/// - file: The file where the failure occurs.
/// The default is the filename of the test case where you call this function.
/// - line: The line number where the failure occurs.
/// The default is the line number where you call this function.
/// - errorHandler: An optional handler for errors that expression throws.
func assertThrowsAsyncError<T>(
_ expression: @autoclosure () async throws -> T,
_ message: @autoclosure () -> String = "",
file: StaticString = #filePath,
line: UInt = #line,
_ errorHandler: (_ error: Error) -> Void = { _ in }
) async {
do {
_ = try await expression()
// expected error to be thrown, but it was not
let customMessage = message()
if customMessage.isEmpty {
XCTFail("Asynchronous call did not throw an error.", file: file, line: line)
} else {
XCTFail(customMessage, file: file, line: line)
}
} catch {
errorHandler(error)
}
}
I’ve posted this as a file that can be added to the unit test target of your projects:
https://gitlab.com/-/snippets/2567566