Skip to content

Instantly share code, notes, and snippets.

@abey
Last active August 14, 2020 17:42
Show Gist options
  • Save abey/93157991eb92b70d9a1c435da11269c1 to your computer and use it in GitHub Desktop.
Save abey/93157991eb92b70d9a1c435da11269c1 to your computer and use it in GitHub Desktop.
Load JSON file
import XCTest
extension XCTest {
func loadFromJSON<T: Codable>(jsonFileName filename: String) -> T? {
guard let url = Bundle(for: type(of: self)).url(forResource: filename, withExtension: "json") else {
XCTFail("Unable to read \(filename) from stub")
return nil
}
do {
let contents = try Data(contentsOf: url)
return try JSONDecoder().decode(T.self, from: contents)
} catch {
XCTFail("Unable to read \(filename) from stub")
return nil
}
}
// wrapper for removing nil value
func fromJson<T: Codable>(_ filename: String) -> T {
return loadFromJSON(jsonFileName: filename)!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment