I'm trying to test for equality among Realm
objects in unit tests. However, I'm unable to get objects to return true
for their equality.
According to the Realm docs here, I should be able to do that:
let expectedUser = User()
expectedUser.email = "help@realm.io"
XCTAssertEqual(testRealm.objects(User.self).first!,
expectedUser,
"User was not properly updated from server.")
However, I get the following test failure with the following code:
Realm Model
class Blurb: Object {
dynamic var text = ""
}
Test
func testRealmEquality() {
let a = Blurb()
a.text = "asdf"
let b = Blurb()
b.text = "asdf"
XCTAssertEqual(a, b)
}
XCTAssertEqual failed: ("Optional(Blurb {
text = asdf;
})") is not equal to ("Optional(Blurb {
text = asdf;
})")
Do you know how comparison protocols works on iOS?
If you don't, check here http://nshipster.com/swift-comparison-protocols/
Basically if you do
You should create a class like this conform to Equatable
I suggest to check .text for testing
Katsumi from Realm here. Realm object's
Equatable
is implemented as follows:In summary, a) if both objects are unmanaged, it works same as normal object's
Equatable
. b) if both objects are managed, if they are the same table (class) and index, they are equal. c) If one is managed, another is unmanaged, ther are not equal."managed" means the object has stored in Realm.
So
a
andb
in your code is not equal. Becausea
andb
are unmanaged (have not stored in Realm) and they are different objects.Furthermore, when testing the equality, Realm doesn't care the values of the objects. Realm checks only a table and row index (as mentioned "b)"). Because different objects that has the same value are stored in the database is normal.
An example that two objects are equal is like the following: