XCTAssertEqual does not work for Equatable types in Swift

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 test case:

 func testExample() { let a = TestObject(a: 4) let b = TestObject(a: 4) XCTAssertEqual(a, b) // fails let isEqual = a == b XCTAssert(isEqual) // passes } 

both statements return different values, but both must 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 it also fails:

 BAAssertEquatable(a, b, "custom assert") // fails 

What's going on here?

+7
swift xctest
source share
1 answer

XCTAssertEqual calls isEqual instead of == , for example. this will make your test pass:

 class TestObject: NSObject { // ... override func isEqual(object: AnyObject?) -> Bool { guard let other = object as? TestObject else { return false } return self == other } } 
+3
source share

All Articles