Skip to content

Instantly share code, notes, and snippets.

@yasirmturk
Last active December 14, 2021 19:50
Show Gist options
  • Save yasirmturk/b77c34cf3fc37267dbdd78e0a5bf8e38 to your computer and use it in GitHub Desktop.
Save yasirmturk/b77c34cf3fc37267dbdd78e0a5bf8e38 to your computer and use it in GitHub Desktop.
Protocol to create models from json
import Foundation
final class MockableTests {
struct MockNotFound: Error {
let message: String
}
}
extension Bundle {
static let tests = Bundle(for: MockableTests.self)
}
protocol ModelMockable: Decodable {
static func mock(fileName: String) throws -> Self
}
extension ModelMockable {
// tries to find <Model>.json file in test bundle
static func mock(fileName: String = "\(Self.self)") throws -> Self {
guard let jsonURL = Bundle.tests.url(forResource: fileName, withExtension: "json") else {
throw MockableTests.MockNotFound(message: "Unable to find json mocks for \(fileName)")
}
let json = try Data(contentsOf: jsonURL)
return try JSONDecoder().decode(Self.self, from: json)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment