Maybe1 Maybe1 - 4 months ago 15
JSON Question

Unit testing JSON Swift

I am working on an iOS application written in Swift which parse a lot of JSON files.
The JSON structures are sophisticated and I would to test them before to map JSON to object.

For example test if the key 'users' exists and for each user the structure('name', 'first', 'last').

{
"users": [
{
"name": {
"first": "emmi",
"last": "wiita"
}
},
{
"name": {
"first": "erdi",
"last": "nielen"
}
},
{
"name": {
"first": "daniel",
"last": "beck"
}
}
]
}


Are there any good way to do this?

Thanks.

Answer

Thank you for your post @Felipe Plets. I found a good way to test JSON file.

I have implemented an enum ErrorType(Exception):

/**
 Enumeration describing possible errors that occur while parsing 
 a message from JSON file.
*/
enum ReceiverError: ErrorType {
    /**
     Error trigge when the key is missed or the type.
     - Parameter key: Key missed.
    */
    case MissingKeyOrType(key: String)
}

then I can test all the JSON file like this:

func isValidJSON(message: [String: AnyObject]) -> throws {
    guard let sosId = message["id"] as? String 
        else { throw ReceiverError.MissingKeyOrType(key: "sos - id") }
    guard let text = message["text"] as? String 
        else { throw ReceiverError.MissingKeyOrType(key: "text")
}

let json = ... Get JSON

do {
   try isValidJSON(json)
} catch CustomReceiver.ReceiverError.MissingKeyOrType(let key) {
   print("Error: Missing key or type [key: \(key)].")
}