如何伪造Realm结果进行测试 [英] How to fake Realm Results for tests

查看:88
本文介绍了如何伪造Realm结果进行测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一个测试来验证是否调用了一个函数:

I have written a test to validate if a function is called :

  func test_getTaskLists_doNotCreateOrUpdateTaskListToStorageWhenSynchedLocally() {

   ...    
    let (datasource, restAPI, fakeTaskListStorage) = ...

    datasource.getTaskLists() { (taskLists, error) -> Void in
      ...
      XCTAssertEqual(1, fakeTaskListStorage.readAllInvocationCount)
      ...      
    }
...
  }

该函数被模拟为绕过超级实现,问题是该函数返回一个我无法弄清楚要返回有效对象的结果,因此编译器不再抱怨...我知道我可以只调用super.readAll(),但实际上我想将测试数据(fakeTaskLists)转换为伪造的Result对象,以便每个人都很高兴...不确定那是否可能

The function is mocked to bypass super implementation and the issue is that the function returns a Results which I can't figure out to build/mock in order to return a valid object so the compiler stops complaining...I know I could just call super.readAll() but here I actually want to convert my test data (fakeTaskLists) to a fake Result object so everyone is happy...not sure if thats possible

class FakeTaskListsStorageRealm : TaskListStorageRealm {
    var fakeTaskLists:[TaskList]?
    override func readAll() -> RealmSwift.Results<TaskList> {
      readAllInvocationCount += 1
      //Here I want to return fakeTaskLists somehow...
    }
}

推荐答案

无法直接实例化Results.子类化Results也是不允许的.我认为最好的方法是通过像ResultsWrapper这样的协议隐藏Results,而不是直接使用Results.

There is no way to instantiate Results directly. Subclassing Results doesn't allow too. I think the best way is hiding Results by protocol like ResultsWrapper rather than using Results directly.

但是一个简单的解决方法是在测试时使用内存领域. FakeTaskListsStorageRealmreadAll()可以使用内存领域来编写,如下所示:

But an easy workaround is using in-memory Realm when testing. The FakeTaskListsStorageRealm's readAll() can be written using in-memory Realm as follows:

class FakeTaskListsStorageRealm : TaskListStorageRealm {
    var fakeTaskLists:[TaskList]?
    override func readAll() -> RealmSwift.Results<TaskList> {
        readAllInvocationCount += 1
        return try! Realm(configuration: Realm.Configuration(inMemoryIdentifier: "test")).objects(TaskList.self)
    }
}

这篇关于如何伪造Realm结果进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆