-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExample.swift
More file actions
100 lines (86 loc) · 2.55 KB
/
Copy pathExample.swift
File metadata and controls
100 lines (86 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
//
// ChildFragment.swift
// Example
//
// Created by Coruț Fabrizio on 18.03.2021.
// Copyright © 2021 Shortcut AS. All rights reserved.
//
import XCTest
import Foundation
struct Pokemon: Codable {
enum `Type`: String, CaseIterable {
case normal
case fire
case fighting
case water
case flying
case grass
case poison
case electric
case ground
case psychic
case rock
case ice
case bug // NO, not an actual bug in the code.
case dragon
case ghost
case dark
case steel
case fairy
/// If none of the above ones are provided.
case undefined
}
/// The core strength of the `Pokemon`.
let baseType: `Type`
/// Every `Pokemon` must have a name.
let name: String
/// `nil` if the `Pokemon` has not been seen before.
let pokedexIndex: Int?
}
final class PokemonJSONFragment: ModelJSONFragment<PokemonJSONFragment.Keys> {
enum Keys: String {
case baseType, name, pokedexIndex
}
convenience init(baseType: String? = Pokemon.`Type`.fire.rawValue,
name: String? = "Charizard",
pokedexIndex: Int? = 6) {
self.init(referenceValues: [ .baseType: baseType, .name: name, .pokedexIndex: pokedexIndex ])
}
override func compareCurrentFragment(to model: Any) {
guard let model = model as? Pokemon else { return }
XCTAssertEqual(referenceValues[.baseType] as? String, model.baseType.rawValue)
XCTAssertEqual(referenceValues[.name] as? String, model.name)
XCTAssertEqual(referenceValues[.pokedexIndex] as? Int, model.pokedexIndex)
}
}
final class PokemonParsingTests: XCTestCase {
func testDefaultValues() throws {
let jsonRepresentation = PokemonJSONFragment().toJSON()
let model = try JSONDecoder().decode(Pokemon.self, from: jsonRepresentation.data)
jsonRepresentation.compare(to: model)
}
func testBaseTypesValues() throws {
let decoder = JSONDecoder()
try Pokemon.`Type`.allCases.forEach {
let jsonRepresentation = PokemonJSONFragment(baseType: $0.rawValue)
.toJSON()
let model = try decoder.decode(Pokemon.self, from: jsonRepresentation.data)
jsonRepresentation.compare(to: model)
}
}
func testNonNullable() throws {
let decoder = JSONDecoder()
try [PokemonJSONFragment(baseType: nil), PokemonJSONFragment(name: nil)]
.lazy
.map { $0.toJSON() }
.forEach {
let model = try? decoder.decode(Pokemon.self, from: $0.data)
XCTAssertNil(model)
}
}
func testNullable() throws {
let jsonRepresentation = PokemonJSONFragment(pokedexIndex: nil).toJSON()
let model = try JSONDecoder().decode(Pokemon.self, from: jsonRepresentation.data)
jsonRepresentation.compare(to: model)
}
}