What is the replacement for XCTAssertEqualObjects?

人走茶凉 提交于 2020-01-16 01:19:32

问题


Not sure exactly when but at least as of Xcode 7.2, XCTAssertEqualObjects is no longer available.

Is there a replacement for this without having to resort to?

   XCTAssertTrue(foo == bar)

Note that Apple's "Writing Test Classes and Methods" appears out of date and still refers to the missing class.


回答1:


I would be a bit more specific about what you are testing.

Equality and identity are not the same thing, especially in Swift where there are far richer value types.

If you want to test equality as defined by conformance to Equatable then use:

XCTAssertTrue(a == b)

If you want to test that two reference types are equal:

XCTAssertTrue(a === b)

I feel this is better because the assertion is more explicit; are the objects equal or identical.

Remember the WWDC15 session on Value Types in Swift - which recommends always making your value types conform to Equatable.




回答2:


For Swift you can just use XCTAssertEqual.

Your objects need to implement the Equatable protocol so the macro can use ==.


Example:

import XCTest

class A: Equatable {
    let name: String
    init(name: String) {
        self.name = name
    }
}
func ==(lhs: A, rhs: A) -> Bool {
    return lhs.name == rhs.name
}

class FooTests: XCTestCase {
    func testFoo() {
        let a = A(name: "foo")
        let a1 = A(name: "foo")
        let b = A(name: "bar")
        XCTAssertEqual(a, a)
        XCTAssertEqual(a, a1)
        XCTAssertEqual(a, b)    // will fail
    }
}


来源:https://stackoverflow.com/questions/34764509/what-is-the-replacement-for-xctassertequalobjects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!