Skip to content

Instantly share code, notes, and snippets.

@CassiusPacheco
Last active September 14, 2022 04:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CassiusPacheco/7c5144a37ab96b2ff13e697f9927da30 to your computer and use it in GitHub Desktop.
Save CassiusPacheco/7c5144a37ab96b2ff13e697f9927da30 to your computer and use it in GitHub Desktop.
Helper for easily asserting an async method threw an error
import Foundation
import XCTest
extension XCTestCase {
/// Expects that the async code will throw
@discardableResult
func XCTAssertThrowsErrorAsync(
testName: String = #function,
file: StaticString = #filePath,
line: UInt = #line,
test: () async throws -> Void
) async -> Error? {
do {
try await test()
XCTFail("\(testName) should have failed", file: file, line: line)
return nil
} catch {
// Success
return error
}
}
}
@CassiusPacheco
Copy link
Author

Usage example:

enum MyError: Error {
    case something
}

struct MyStruct {
    func throwableMethod() async throws {
        throw MyError.something
    }
}

final class MyStructTests: XCTestCase {
    func testMethodThrows() async {
        await XCTAssertThrowsErrorAsync {
            try await MyStruct().throwableMethod()
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment