Let's say you have a JSON with several fields:
Students: [
student: {
name: "Harry"
surname: "Smith"
age: 24
},
...
]
and decodables:
struct Students : Decodable {
let student: [Student]
}
struct Student : Decodable {
let name: String
let surname: String
let age: Int
}
If you want to test invalid data, do you write a sequence of tests with te following fake data?
Test1 data:
{
name: null
surname: "Smith"
age: 24
}
Test2 data:
{
name: "Harry"
surname: null
age: 24
}
Test3 data:
{
name: "Harry"
surname: "Smith"
age: null
}
And maybe a test with a wrong type?
{
name: "Harry"
surname: "Smith"
age: "24" //<- string
}
So do you write all these tests, one for each of the above jsons or does this not make sense to you?
It makes sense writing separate test for each key-value pair if we were not able to see the reason of failure and we had to handle it ourself for each pair. For example, old way of JSONSerialization to get Dictionary and then manually checking each key-value if they exist, if yes, does type matches etc. If we were able to get all the values and expected then we would use to initialize the type e.g, Student. In this kind of scenario, instead of putting so many if-else to report proper failure one can think of separate cases for each pair.
Now that we have Codable and error thrown clearly provide all the information for failure so a single test is enough.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With