如何与XCTAssertEqual比较可选的模型属性

时间:2014-08-13 05:48:53

标签: ios swift xctest

是否有更好的方法来比较我的模型对象中的值,而不是下面的代码片段,它看起来非常详细,而且只针对一个属性?

模型对象

struct Address {

    static let kADDRESS1 = "address1"
    static let kADDRESS2 = "address2"
    static let kADDRESS3 = "address3"
    static let kCITY = "city"
    static let kSTATE = "state"
    static let kPOSTAL_CODE = "postalCode"

    var address1:String?,
    address2:String?,
    address3:String?,
    city:String?,
    state:String?,
    postalCode:String?

    init(address1: String?,
            address2: String?,
            address3: String?,
            city: String?,
            state: String?,
        postalCode: String?) {
            self.address1 = address1;
            self.address2 = address2;
            self.address3 = address3;
            self.city = city;
            self.state = state;
            self.postalCode = postalCode;

    }
    init(params:NSDictionary) {
        self.init(address1: params.objectForKey("address1") as String?,
            address2: params.objectForKey("address2") as String?,
            address3: params.objectForKey("address3") as String?,
            city: params.objectForKey("city") as String?,
            state: params.objectForKey("state") as String?,
            postalCode: params.objectForKey("state") as String?)
    }
}

来自测试用例    func testCreateAddress(){

let params:NSDictionary = [Address.kADDRESS1: "1 Main St.", Address.kADDRESS2: "Apt. 1", Address.kADDRESS3: "Box 1", Address.kCITY: "San Francisco", Address.kSTATE: "CA", Address.kPOSTAL_CODE: "7899"];

let address = Address(params:params);

if let param  = params[Address.kADDRESS1] as String? {
    if let property = address.address1 {
        XCTAssertEqual(property, param)
    }
    else {
        XCTFail("properties do not match")
    }
}
else {
    if let property = address.address1 {
        XCTFail("properties do not match")
    }
}

}

2 个答案:

答案 0 :(得分:1)

我认为你可以在测试中假设一些事情:

  1. XCTAssertEqual会让您的测试失败(出现相应的错误 消息)如果字符串不相等,因此您不需要任何XCTFail

  2. params[Address.kADDRESS1]肯定是您刚刚定义的 上述

  3. 所以我建议将测试改为:

    let params:NSDictionary = [Address.kADDRESS1: "1 Main St.", Address.kADDRESS2: "Apt. 1", Address.kADDRESS3: "Box 1", Address.kCITY: "San Francisco", Address.kSTATE: "CA", Address.kPOSTAL_CODE: "7899"]
    
    let address = Address(params:params)
    XCTAssertNotNil(address.address1)
    XCTAssertEqual(address.address1!, params[Address.kADDRESS1], "address1 should be set")
    

    我承认,如果address.adress1为nil,您将获得运行时异常,因为XCTAssertEqual将无法解包该变量,但XCTAssertNotNil将事先失败,因此您知道& #39;正在发生。

答案 1 :(得分:0)

我想我发现了一种更简洁的方式:

    if(address.address1? != nil && params[Address.kADDRESS1]? != nil) {
        XCTAssertEqual(address.address1!, params[Address.kADDRESS1]!)
    }