简体   繁体   中英

XCTest for test model objects

Bellow i have mentioned my model object.

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
        }
    }
}

then i implemented a test case to check variables. Bellow i have mentioned the test case.

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")
}

bellow i have mentioned the error

XCTAssertEqual failed: ("nil") is not equal to ("Optional("Lasantha")")

please help me to fix the issue

Your problem is that you cannot use

_data.objectForKey("last_name")

in your HVConnection because it is nested within another dictionary key called network .

So instead use:

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

This is to demonstrate the dictionaries in use:

["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"]
]

In order to get your last_name , you have to get the dictionary for key network to get the actual dictionary, and once you have that, you can check that dictionary you get back from the network key for the key last_name .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM