Skip to content

Instantly share code, notes, and snippets.

@PaulTaykalo
Last active July 16, 2018 11:20
Show Gist options
  • Save PaulTaykalo/72a8a117f26bdb71358c833238dc3001 to your computer and use it in GitHub Desktop.
Save PaulTaykalo/72a8a117f26bdb71358c833238dc3001 to your computer and use it in GitHub Desktop.
Error failable
public extension XCTestCase {
// We conform to LocalizedError in order to be able to output
// a nice error message.
private struct RequireError<T>: LocalizedError {
let file: StaticString
let line: UInt
// It's important to implement this property, otherwise we won't
// get a nice error message in the logs if our tests start to fail.
var errorDescription: String? {
return "😱 Required value of type \(T.self) was nil at line \(line) in file \(file)."
}
}
// Using file and line lets us automatically capture where
// the expression took place in our source code.
public func require<T>(_ expression: @autoclosure () throws -> T? ,
file: StaticString = #file,
line: UInt = #line) throws -> T {
guard
let optionalValue = try? expression(),
let value = optionalValue else {
let error = RequireError<T>(file: file, line: line)
XCTFail(error.errorDescription ?? "", file: file, line: line)
throw error
}
return value
}
}
@PaulTaykalo
Copy link
Author

image

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