如何伪造Realm结果进行测试 [英] How to fake Realm Results for tests
问题描述
我已经编写了一个测试来验证是否调用了一个函数:
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.
但是一个简单的解决方法是在测试时使用内存领域.
FakeTaskListsStorageRealm
的readAll()
可以使用内存领域来编写,如下所示:
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屋!