Skip to content

Instantly share code, notes, and snippets.

@hishma
Last active July 30, 2019 18:30
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 hishma/2165c390b81d70d5cba14b33c94ba1ef to your computer and use it in GitHub Desktop.
Save hishma/2165c390b81d70d5cba14b33c94ba1ef to your computer and use it in GitHub Desktop.
import XCTest
extension XCTestCase {
/// Asserts that an expression throws a specific error.
///
/// - Parameters:
/// - expression: An expression that can throw an error.
/// - throws: The expected `Error`. Must conform to the `Equatable` protocol.
/// - file: The file in which failure occurred. Defaults to the file name of the test case in which this function was called.
/// - line: The line number on which failure occurred. Defaults to the line number on which this function was called.
func assert<T, E: Error & Equatable>(_ expression: @autoclosure () throws -> T, throws expectedError: E, in file: StaticString = #file, line: UInt = #line ) {
var thrownError: Error?
XCTAssertThrowsError(try expression(), file: file, line: line) {
thrownError = $0
}
guard let error = thrownError else { return }
guard error is E else {
XCTFail("Unexpected error type: \(type(of: error))", file: file, line: line)
return
}
XCTAssertEqual(error as? E, expectedError, file: file, line: line)
}
/// Asserts that an expression throws a specific CocoaError.
///
/// - Parameters:
/// - expression: An expression that can throw an error.
/// - errorCode: The expected `CocoaError.code`.
/// - file: The file in which failure occurred. Defaults to the file name of the test case in which this function was called.
/// - line: The line number on which failure occurred. Defaults to the line number on which this function was called.
func assert<T>(_ expression: @autoclosure () throws -> T, throwsCocoaErrorCode errorCode: CocoaError.Code, in file: StaticString = #file, line: UInt = #line) {
var thrownError: Error?
XCTAssertThrowsError(try expression(), file: file, line: line) {
thrownError = $0
}
guard let error = thrownError else { return }
guard let cocoaError = error as? CocoaError else {
XCTFail("Unexpected error type: \(type(of: error))", file: file, line: line)
return
}
XCTAssertEqual(cocoaError.code, errorCode, file: file, line: line)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment