Last active
December 14, 2021 19:50
-
-
Save yasirmturk/b77c34cf3fc37267dbdd78e0a5bf8e38 to your computer and use it in GitHub Desktop.
Protocol to create models from json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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