Given the following Swift class:
class TestObject: NSObject {
let a: Int
init(a: Int) {
self.a = a
super.init()
}
}
func ==(lhs: TestObject, rhs: TestObject) -> Bool {
return lhs.a == rhs.a
}
and a test case for it:
func testExample() {
let a = TestObject(a: 4)
let b = TestObject(a: 4)
XCTAssertEqual(a, b) // fails
let isEqual = a == b
XCTAssert(isEqual) // passes
}
the two assert's return different values, but they should both pass.
I tried writing a custom assert function:
func BAAssertEquatable<A: Equatable>(x1: A, _ x2: A, _ message: String, file: String = __FILE__, line: UInt = __LINE__) {
let operandsEqual = (x1 == x2)
XCTAssert(operandsEqual, message, file: file, line: line)
}
but this also fails:
BAAssertEquatable(a, b, "custom assert") // fails
What's going on here?
XCTAssertEqual
calls isEqual
instead of ==
, e.g. this will make your test pass:
class TestObject: NSObject {
// ...
override public func isEqual(_ object: Any?) -> Bool {
guard let other = object as? TestObject else { return false }
return self == other
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With