ios – 在领域中测试平等
发布时间:2020-12-15 01:46:50 所属栏目:百科 来源:网络整理
导读:我试图在单元测试中测试Realm对象之间的相等性.但是,我无法让对象为了平等而返回true. 根据Realm docs here,我应该能够这样做: let expectedUser = User()expectedUser.email = "help@realm.io"XCTAssertEqual(testRealm.objects(User.self).first!,expecte
我试图在单元测试中测试Realm对象之间的相等性.但是,我无法让对象为了平等而返回true.
根据Realm docs here,我应该能够这样做: let expectedUser = User() expectedUser.email = "help@realm.io" XCTAssertEqual(testRealm.objects(User.self).first!,expectedUser,"User was not properly updated from server.") 但是,我使用以下代码获得以下测试失败: 境界模型 class Blurb: Object { dynamic var text = "" } 测试 func testRealmEquality() { let a = Blurb() a.text = "asdf" let b = Blurb() b.text = "asdf" XCTAssertEqual(a,b) }
解决方法
来自Realm的Katsumi在这里. Realm对象的Equatable实现如下:
BOOL RLMObjectBaseAreEqual(RLMObjectBase *o1,RLMObjectBase *o2) { // if not the correct types throw if ((o1 && ![o1 isKindOfClass:RLMObjectBase.class]) || (o2 && ![o2 isKindOfClass:RLMObjectBase.class])) { @throw RLMException(@"Can only compare objects of class RLMObjectBase"); } // if identical object (or both are nil) if (o1 == o2) { return YES; } // if one is nil if (o1 == nil || o2 == nil) { return NO; } // if not in realm or differing realms if (o1->_realm == nil || o1->_realm != o2->_realm) { return NO; } // if either are detached if (!o1->_row.is_attached() || !o2->_row.is_attached()) { return NO; } // if table and index are the same return o1->_row.get_table() == o2->_row.get_table() && o1->_row.get_index() == o2->_row.get_index(); } 总之,a)如果两个对象都是非托管的,它的工作方式与普通对象的Equatable相同. b)如果两个对象都被管理,如果它们是相同的表(类)和索引,它们是相等的. c)如果管理一个,另一个不受管理,则不相等. “托管”表示对象已存储在Realm中. 所以代码中的a和b不相等.因为a和b是不受管理的(没有存储在Realm中)并且它们是不同的对象. let a = Blurb() a.text = "asdf" let b = Blurb() b.text = "asdf" XCTAssertEqual(a.text,b.text) 此外,在测试相等性时,Realm不关心对象的值.领域只检查表和行索引(如“b)”所述.因为具有相同值的不同对象存储在数据库中是正常的. 两个对象相等的示例如下所示: let a = Blurb() a.text = "asdf" let realm = try! Realm() try! realm.write { realm.add(a) } let b = realm.objects(Blurb.self).first! print(a == b) // true (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |