测试模型对象的XCTest

时间:2016-01-04 10:31:05

标签: ios xcode swift unit-testing xctest

贝娄我提到了我的模型对象。

class HVConnection: NSObject {

    //private var _data: NSMutableDictionary
    private var _data: NSMutableDictionary

    // MARK:- Init

    init(data: NSDictionary)
    {
        _data = NSMutableDictionary(dictionary: data)
    }

    // MARK:- Properties
    var last_name: String? {
        if let lastNameObject = _data.objectForKey("last_name") {
            return (idObject as! String)
        } else {
            return nil
        }
    }
}

然后我实现了一个测试用例来检查变量。 贝娄我已经提到了测试用例。

func testNetworkModelObject() {

    let connectionObject = ["network": ["first_name": "Dimuth", "last_name": "Lasantha", "business_email": "example@gmail.com", "currency": "USD", "language": "en-us", "category": "individual"]]
    let modelObject = HVConnection(data: connectionObject)

    XCTAssertEqual(modelObject.last_name, "Lasantha")
}

下面我提到了错误

  

XCTAssertEqual失败:(" nil")不等于("可选(" Lasantha")")

请帮我解决问题

1 个答案:

答案 0 :(得分:0)

您的问题是您无法使用

_data.objectForKey("last_name")

HVConnection中,因为它嵌套在另一个名为network的词典键中。

所以改为使用:

// MARK:- Properties
var last_name: String? {
    if let lastNameObject = _data.objectForKey("network")?.objectForKey("last_name") {
        return (lastNameObject as! String)
    } else {
        return nil
    }
}

这是为了演示正在使用的词典:

["network": // your dictionary is a dictionary within a dictionary
    ["first_name": "Dimuth", 
     "last_name": "Lasantha", 
     "business_email": "example@gmail.com", 
     "currency": "USD", 
     "language": "en-us", 
     "category": "individual"]
]

为了获得last_name,您必须获取密钥network的字典才能获得实际的字典,一旦有了,您就可以检查从{{{}}获取的字典。密钥network的密钥{1}}。