Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XCTAssertEqual not working for Equatable types in Swift

Tags:

swift

xctest

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?

like image 601
Bill Avatar asked Sep 10 '15 11:09

Bill


1 Answers

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
    }
    
}
like image 187
Rudolf Adamkovič Avatar answered Nov 14 '22 02:11

Rudolf Adamkovič