如何XCTA一次比较几个比较?

时间:2017-04-23 21:00:33

标签: swift unit-testing

我有一个包含三个属性的实例。我想在同一个XCTAssert中验证所有三个属性。这可能吗?

例如,而不是这样做:

XCTAssertEqual(myItem.name, "John Doe")
XCTAssertEqual(myItem.age, 35)
XCTAssertEqual(myItem.deptId, 1001)

有没有办法在同一个XCTAssert中完成所有操作?

1 个答案:

答案 0 :(得分:3)

假设这是你的Item结构:

struct Item {
    let name: String
    let age: Int
    let deptID: Int
}
  1. 符合Equatable,并定义==对[{1}})的平等含义:

    Item
  2. extension Item: Equatable { static func ==(lhs: Item, rhs: Item) -> Bool { return lhs.name == rhs.name && lhs.age == rhs.age && lhs.deptID == rhs.deptID } } 运算符编写测试:

    ==
  3. 从现在开始,你可以用以下方法检查相等性(在其他测试中):

    func testItemEquality() {
        let original = Item(name: "name", age: 0, deptID: 0)
    
        let differentName = Item(
            name: "different " + original.name,
            age: original.age,
            deptID: original.deptID
        )
    
        let differentAge = Item(
            name: original.name,
            age: original.age + 1,
            deptID: original.deptID
        )
    
        let differentDeptID = Item(
            name: original.name,
            age: original.age,
            deptID: original.deptID + 1
        )
    
        let completelyDifferent = Item(
            name: "different " + original.name,
            age: original.age + 1,
            deptID: original.deptID + 1
        )
    
        XCTAssertEqual(original, original)
    
        XCTAssertNotEqual(original, differentName)
        XCTAssertNotEqual(original, differentAge)
        XCTAssertNotEqual(original, differentDeptID)
        XCTAssertNotEqual(original, completelyDifferent)
    
        XCTAssertNotEqual(differentName, differentAge)
        XCTAssertNotEqual(differentName, differentDeptID)
        XCTAssertNotEqual(differentName, completelyDifferent)
    
        XCTAssertNotEqual(differentAge, differentDeptID)
        XCTAssertNotEqual(differentAge, completelyDifferent)
    
        XCTAssertNotEqual(differentDeptID, completelyDifferent)
    }