Skip to content

Instantly share code, notes, and snippets.

@daehn
Created July 9, 2019 14:42
Show Gist options
  • Save daehn/57b1e074511643ef00db1a97b89c831b to your computer and use it in GitHub Desktop.
Save daehn/57b1e074511643ef00db1a97b89c831b to your computer and use it in GitHub Desktop.
extension XCTestCase {
enum FixtureError: Error {
case resourceNotFound
case invalidFormat
}
/// Loads the json fixture with the given name from disk and returns a json object.
/// - Parameter fileName: The anme of the fixture on disk (without the type suffix).
/// - Throws: Any errors encountered during the process.
func jsonFixture(named fileName: String) throws -> [String: Any] {
let bundle = Bundle(for: type(of: self))
let path = bundle.path(forResource: fileName, ofType: "json")
guard let url = path.flatMap(URL.init(fileURLWithPath:)) else { throw FixtureError.resourceNotFound }
let data = try Data(contentsOf: url)
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else { throw FixtureError.invalidFormat }
return json
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment