2

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.

Max MacLeod
  • 26,115
  • 13
  • 104
  • 132

2 Answers2

4

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
    }
}
Pascal
  • 16,846
  • 4
  • 60
  • 69
  • doesn't work unfortunately. See my comment on http://stackoverflow.com/questions/25341705/xctassertequal-for-custom-objects-in-swift XCTAssertEqual does not trigger the breakpoint in my custom implementation of ==. XCTAssertEqual appears to return based upon object equivalence. To trigger my == func I have to specify XCTAssertTrue(a == b) – Max MacLeod Jan 13 '16 at 10:56
  • @MaxMacLeod `XCTAssertEquals` does make use of the equality operator. Perhaps the problem lies somewhere else in your code. – Cristik Jan 13 '16 at 11:01
  • @MaxMacLeod I've added an example, setting a breakpoint in the `==` func stops execution three times. – Pascal Jan 13 '16 at 11:52
  • 1
    @MaxMacLeod: If the class inherits from NSObject then you probably have to override `isEqual:` instead of `==`. Compare http://stackoverflow.com/questions/33319959/nsobject-subclass-in-swift-hash-vs-hashvalue-isequal-vs. – Martin R Jan 13 '16 at 12:05
  • @Cristik yes I do subclass NSObject so it's already implementing Equatable. That could be the issue. I'll give Martin R's suggestion a try. – Max MacLeod Jan 13 '16 at 12:46
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.

Abizern
  • 146,289
  • 39
  • 203
  • 257