Quick / Nimble

A Matcher Framework for Swift and Objective-C
https://quick.github.io/Nimble/documentation/nimble/
Apache License 2.0
4.8k stars 596 forks source link

Predicate equal doesn't work as expected with NSObject #1082

Open georgemp opened 11 months ago

georgemp commented 11 months ago

What did you do?

Create an NSObject (in Swift) that conforms to Comparable and implements isEqual(to: Any?).

import Cocoa

public class Tiger: NSObject {
    let id: Int
    let name: String

    init(id: Int, name: String) {
        self.id = id
        self.name = name
    }
}

extension Tiger {
    public override func isEqual(to object: Any?) -> Bool {
        guard let rhs = object as? Tiger else {
            return false
        }

        return self.id == rhs.id && self.name == rhs.name
    }
}

extension Tiger: Comparable {
    public static func < (lhs: Tiger, rhs: Tiger) -> Bool {
        return lhs.id < rhs.id
    }

    public static func == (lhs: Tiger, rhs: Tiger) -> Bool {
        return lhs.isEqual(to: rhs)
    }
}

Compared instances of the Tiger object using predicate equal

import XCTest
@testable import NimblePackage
import Nimble

final class NimblePackageTests: XCTestCase {
    func testExample() throws {
        let tiger1 = Tiger(id: 1, name: "Sher Khan")
        let tiger1Copy = Tiger(id: 1, name: "Sher Khan")
        let tiger2 = Tiger(id: 2, name: "Tigger")

        expect(tiger1 == tiger1Copy).to(beTrue()) //Passes
        expect(tiger1).to(equal(tiger1)) //Passes
        expect(tiger1).to(equal(tiger1Copy)) //Fails
        expect(tiger1 != tiger2).to(beTrue()) //Passes
    }
}

What did you expect to happen?

Expected the objects to be compared using the implementation of the Equatable protocol and to return true.

What actually happened instead?

Instead, they are compared by pointer to see if they are the same object and returns false.

Environment

List the software versions you're using:

Please also mention which package manager you used and its version. Delete the other package managers in this list: