-
-
Save bkobilansky/1b210dde0bea1e122f49df64c7cd2f35 to your computer and use it in GitHub Desktop.
A function that asserts that an expression throws a given error
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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