XCode 6,Beta 5
XCode 6, Beta 5
我有这样的单元测试:
func testMyObjectsEqual() { //.... XCTAssertEqual(myObject, myOtherObject, "\(myObject) and \(myOtherObject) should be equal") }XCTAssertEqualObjects在Swift中不再可用,因为语言没有标量和对象之间的区别。
XCTAssertEqualObjects is no longer available in Swift since the language makes no distinction between scalars and objects.
所以我们必须使用XCTAssertEqual,这会导致以下错误:
So we have to use XCTAssertEqual which leads to the following error:
"Type MyObject does not conform to protocol Equatable"我发现的唯一解决方法是从NSObject继承(MyObject)以便我可以执行以下:
The only workaround I have found is to inherit (MyObject) from NSObject so that I can do the following:
XCTAssert(myObject == myOtherObject, "\(myObject) and \(myOtherObject) should be equal")所以我的问题是:是否有办法(从测试版5开始)将XCTAssertEqual用于自定义类型而不必依赖o n NSObject或乱丢所有带有==重载的自定义类型?
推荐答案如果你想比较Swift,你可以使用 === 运算符。这是从NSObject继承的情况(当您使用 XCTAssertEqual 比较Objective-C中的对象时,您正在比较引用)。
If you want to compare references in Swift, you can use === operator. This is what happens when you subclass from NSObject (when you are comparing objects in Objective-C using XCTAssertEqual, you are comparing references).
但这真的是你想要的吗?
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 }我想当你比较自定义对象时,你可能应该使它们符合Equatable协议并指定,当你的自定义对象相等时(在下面的例子中,当它们具有相同名称时对象是相同的):
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):
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 }更多推荐
Swift中自定义对象的XCTAssertEqual
发布评论