简体   繁体   中英

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.

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.

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

But I didn't find way to override scheduler in subscribeOn method.How can I do that?

You can pass the below test implementation of ThreadExecutor to the constructor of your UseCase in the test code. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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