Skip to content

Instantly share code, notes, and snippets.

@JohnSundell
Created February 19, 2017 13:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JohnSundell/b7f901e8edb89d1396ede4d8db3e8c21 to your computer and use it in GitHub Desktop.
Save JohnSundell/b7f901e8edb89d1396ede4d8db3e8c21 to your computer and use it in GitHub Desktop.
A function that asserts that an expression throws a given error
/**
* Copyright (c) John Sundell 2017
* Licensed under the MIT license
*/
import Foundation
import XCTest
/**
* Assert that an expression throws a given error
*
* - parameter expression: The expression that should throw an error
* - parameter errorExpression: An expression resulting in an error that should be thrown
* - parameter file: The file in which the assert should take place (automatically inferred)
* - parameter line: The line number at which the assert should take place (automatically inferred)
*
* Usage: `assert(try myFunction(), throwsError: MyError.anError)`
*/
func assert<E: Error>(_ expression: @autoclosure () throws -> Void,
throwsError errorExpression: @autoclosure () -> E,
file: StaticString = #file,
line: UInt = #line) where E: Equatable {
do {
try expression()
XCTFail("Expected expression to throw", file: file, line: line)
} catch let thrownError as E {
let expectedError = errorExpression()
XCTAssert(thrownError == expectedError,
"Incorrect error thrown. \(thrownError) is not equal to \(expectedError)",
file: file,
line: line)
} catch {
XCTFail("Invalid error thrown: \(error)", file: file, line: line)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment