简体   繁体   English

XCTAssertEqual 用于 Swift 中的自定义对象

[英]XCTAssertEqual for custom objects in Swift

XCode 6, Beta 5 XCode 6,测试版 5

I have a unit test like this:我有这样的单元测试:


    func testMyObjectsEqual()
    {
        //....

        XCTAssertEqual(myObject, myOtherObject, "\(myObject) and \(myOtherObject) should be equal")
    }

XCTAssertEqualObjects is no longer available in Swift since the language makes no distinction between scalars and objects. XCTAssertEqualObjects 在 Swift 中不再可用,因为该语言不区分标量和对象。

So we have to use XCTAssertEqual which leads to the following error:所以我们必须使用 XCTAssertEqual 这会导致以下错误:

 "Type MyObject does not conform to protocol Equatable"

The only workaround I have found is to inherit (MyObject) from NSObject so that I can do the following:我发现的唯一解决方法是从 NSObject 继承 (MyObject) 以便我可以执行以下操作:

 XCTAssert(myObject == myOtherObject, "\(myObject) and \(myOtherObject) should be equal")

So my question is: Is there a way (as of beta 5) to use XCTAssertEqual for custom types without having to rely on NSObject or littering all custom types with "==" overloads?所以我的问题是:有没有一种方法(从 beta 5 开始)将 XCTAssertEqual 用于自定义类型,而不必依赖 NSObject 或用“==”重载乱丢所有自定义类型?

If you want to compare references in Swift, you can use === operator. 如果要比较Swift中的引用,可以使用===运算符。 This is what happens when you subclass from NSObject (when you are comparing objects in Objective-C using XCTAssertEqual , you are comparing references). 当您从NSObject XCTAssertEqual子类时会发生这种情况(当您使用XCTAssertEqual比较Objective-C中的XCTAssertEqual ,您正在比较引用)。

But is this really what you want? 但这真的是你想要的吗?

class MyObject {
    var name: String

    init(name: String) {
        self.name = name
    }
}

func testMyObjectsEqual() {
    let myObject = MyObject(name: "obj1")
    let myOtherObject = MyObject(name: "obj1")
    let otherReferenceToMyFirstObject = myObject

    XCTAssert(myObject === myOtherObject) // fails
    XCTAssert(myObject === otherReferenceToMyFirstObject) // passes
}

I guess that when you are comparing custom objects, you probably should make them conform to the Equatable protocol and specify, when your custom objects are equal (in the following case the objects are equal when they have the same name): 我想当你比较自定义对象时,你可能应该使它们符合Equatable协议,并在你的自定义对象相等时指定(在下面的例子中,当它们具有相同名称时对象是相同的):

class MyObject: Equatable {
    var name: String

    init(name: String) {
        self.name = name
    }
}

func ==(lhs: MyObject, rhs: MyObject) -> Bool {
    return lhs.name == rhs.name
}

func testMyObjectsEqual()
{
    let myObject = MyObject(name: "obj1")
    let myOtherObject = MyObject(name: "obj1")

    XCTAssertEqual(myObject, myOtherObject) // passes
}

Since Xcode 12.5 there is XCTAssertIdentical由于 Xcode 12.5 有XCTAssertIdentical

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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