简体   繁体   English

覆盖RxAndroid调度程序进行测试

[英]Overriding RxAndroid Schedulers For Testing

I've seen RxImmediateSchedulerRule usage to override schedulers for testing.But in my case,it doesn't work as I'm using another kind of schedulers -ThreadExecutor and PostExecutionThread from android10 cleanarchitecture github repo. 我已经看过RxImmediateSchedulerRule的用法来覆盖调度程序进行测试。但是,在我的情况下,由于我使用的是android10 cleanarchitecture github存储库中的另一种调度程序-ThreadExecutor和PostExecutionThread,因此它不起作用。

class UseCase(val repo: Repo, val threadExecutor: ThreadExecutor, val postExecutionThread: PostExecutionThread){
    fun execute() = repo.getData()
    .subscribeOn(Schedulers.from(threadExecutor))
    .observeOn(postExecutionThread.scheduler)
}

I'm able to override scheduler in observeOn method with below code. 我可以使用下面的代码覆盖observeOn方法中的调度程序。

whenever(postExecutionThread.scheduler).thenReturn(Schedulers.trampoline())

But I didn't find way to override scheduler in subscribeOn method.How can I do that? 但是我没有找到在SubscribeOn方法中重写Scheduler的方法,该怎么办呢?

You can pass the below test implementation of ThreadExecutor to the constructor of your UseCase in the test code. 您可以在测试代码中将ThreadExecutor的以下测试实现传递给UseCase的构造函数。 This is actually a factory function, which I prefer over derived classes in such cases (but you could use a derived class as well). 实际上,这是一个工厂函数,在这种情况下,我更喜欢派生类(但您也可以使用派生类)。

fun immediateExecutor() : ThreadExecutor {
    return object : ThreadExecutor {
        override fun run(command: Runnable) {
            command.run()
        }
    }
}

It just runs commands immediately, which should be sufficient for unit testing your use cases. 它只是立即运行命令,这足以对用例进行单元测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM