2016-07-14 68 views
4

我正在研究用Swift編寫的iOS應用程序,它解析了很多JSON文件。 JSON結構非常複雜,我會在測試它們之前將JSON映射到對象。單元測試JSON Swift

例如,測試關鍵用戶是否存在,併爲每個用戶測試結構('name','first','last')。

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

有沒有什麼好的方法可以做到這一點?

謝謝。

回答

1

謝謝你的帖子@Felipe Plets。我找到了測試JSON文件的好方法。

我已經實現一個枚舉錯誤類型(例外):

/** 
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) 
} 

然後我可以測試所有JSON文件是這樣的:

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)].") 
} 
1

完成該操作的唯一方法是打開JSON文件並測試每個屬性。

一個好消息是,由於雨燕2.0,你可以使用約束進行測試,如果你可以指定一個有效的值到VAR或出租,這樣你就可以創建一個功能如下:

func isValidJSON(data: NSData) -> Bool { 
    json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) 

    // if "users" exists on the JSON 
    // AND we can cast it to an array of dictionaries 
    guard let users = json["users"] as [[String: AnyObject]] else { 
     return false 
    } 

    for user in users { 
     guard let name = user["name"] as [[String: AnyObject]] 
      firstName = name["first"] as String, 
      lastName = name["last"] as String else { 
       return false 
     } 
    } 

    // valid JSON 
    return true 
} 

最佳實踐也將實現使用異常,而不是在每個警戒語句中返回false。