Kotlinx.coroutines: Test module shall provide ability to replace Dispatchers.IO and Dispatchers.Default

Created on 12 Feb 2019  路  8Comments  路  Source: Kotlin/kotlinx.coroutines

This seems to be as useful for predictable tests as replacing Dispatchers.Main. See discussion in #242 and #890.

enhancement

Most helpful comment

@yigit A test rule is definitely on the radar.

All 8 comments

Note, that since Dispatchers.IO is conceptually a "special view" of Dispatchers.Default (sharing the same thread pool) we might as well just provide an ability to replace Dispatchers.Default with a dispatcher that has an API for creating such views. It would work nicely when such an API is made public (see #261)

I think that fact (using same pool) is not very clear to average developer so I would prefer having them separate APIs to make them match the existing public API.
Unless of course kotlin provides a TestRule that does all of the requests in (#242)

something like:

@RunWith(AndroidJunit::class)
class Test {
    @Rule
    @JvmField
    val dispatchers = CustomDispatchersRule()
}

where CustomDispatchersRule
a) automatically registers to espresso (if possible), or at least implements IdlingResource interface (that is a separate artifact so taking that dependency seems to be OK)
b) provides await methods (dispatchers.awaitIdle(time : long, unit : TimeUnit)).

It could be handy for this class to receive a scheduled executor for further customization though i'm not sure if there is a clear use case for that (vs one that it can create).

@yigit A test rule is definitely on the radar.

Any progress here? Wondering how I should test my code using withContext(Dispatchers.Default) while using runBlockingTest

For now you can probably just inject your Dispatcher so that you can swap it out for TestCoroutineDispatcher in the test

I wrote about using TestCoroutineDispatcher if it's of use to you:

https://craigrussell.io/2019/11/unit-testing-coroutine-suspend-functions-using-testcoroutinedispatcher/

@CDRussell Thanks, actually stumbled upon your blog and implemented that solution 馃憤

Wondering if there is any update on this issue? Just curious on timelines, if there are any.

Was this page helpful?
0 / 5 - 0 ratings