Skip to content

Instantly share code, notes, and snippets.

@bkobilansky
Forked from JohnSundell/AssertThrowsError.swift
Created February 19, 2017 19:19
Show Gist options
  • Save bkobilansky/1b210dde0bea1e122f49df64c7cd2f35 to your computer and use it in GitHub Desktop.
Save bkobilansky/1b210dde0bea1e122f49df64c7cd2f35 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