Kotlinx.coroutines: Integrate test dispatchers with libraries using Dispatchers.Xxx

Created on 23 Jul 2019  路  9Comments  路  Source: Kotlin/kotlinx.coroutines

Make sure that libraries can use hard-coded withContext(Dispatchers.IO) { ... } and still be testable with test dispatchers. See also discussion in #810 and #1202.

test

Most helpful comment

Any update on this issue ?

All 9 comments

The plan is to make TestDefaultDispatcher and TestIoDispatcher similar to TestMainDispatcher and integrate in into kotlinx-coroutines-test as soon as #1206 is here

Any update on this issue ?

I too am curious if there's any update on this issue in 2020. Looking into solutions for unit testing withContext(Dispatchers.IO/Default) calls in my library that doesn't involve dependency injecting it into code where I don't actually want users to be able to provide their own dispatcher.

Why don't you want users to provide your own dispatcher? Any solution here would basically be just another way to replace default dispatcher (just limited to the test library that could be used in production by your users).

You can still use dependency injection without exposing to your consumers. E.g. an internal primary constructor that takes a Dispatcher, and a public secondary constructor that provides a default value. Or a public interface with internal implementation and a public factory function.

@zach-klippenstein This solution does not help me with hardcoded withContext(Dispatchers.IO/Default) in libraries I have a dependency on

Another potential approach to this problem, which still avoids overriding global singletons, would be to bake something like what is proposed in this article into the standard library, and change Dispatchers.* to instead simply indicate which of the DispatcherProvider-provided dispatchers to use (e.g. withContext(Dispatchers.IO) means lookup coroutineContext[DispatcherProvider].io and use that). Then any libraries that take a coroutine context automatically have configurable dispatchers. I'm sure there are still libraries that this still wouldn't solve for, but it feels less hacky for those that it would.

This approach still requires you to have access to the scope/context. If library creates its scope internally, you cannot access that.

This issue keeps coming up for me. Is there anything we can do to help move it along?

Was this page helpful?
0 / 5 - 0 ratings