RBusarow / Dispatch

Automatic CoroutineDispatcher injection and extensions for kotlinx.coroutines

Home Page:https://rbusarow.github.io/Dispatch/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

runBlockingTestProvided() must add the TestCoroutineDispatcher to the context

ralfstuckert opened this issue · comments

The TestCoroutineDispatcher used to create the TestDispatcherProvider is not added to the context. Since there is no existing dispatcher in the context, the called runBlockingTest() will create its own TestCoroutineDispatcher.

As a consequence, any calls to advanceTime...() will not work correctly since they are performed on a different dispatcher. The following test fails with an UncompletedCoroutinesError

    @Test
    @ExperimentalCoroutinesApi
    fun advanceTimeIssue() = runBlockingTestProvided {
        delayOnProvidedMain()
        advanceTimeBy(1000)
    }

    fun CoroutineScope.delayOnProvidedMain() {
        launch(dispatcherProvider.main) {
            delay(1000)
        }
    }

In order to fix this situation, you must add the testDispatcher used for the provider also to the context, see this working example:

    @ExperimentalCoroutinesApi
    private fun contextWithProvider(): CoroutineContext {
        val testDispatcher = TestCoroutineDispatcher()
        val provider = TestDispatcherProvider(testDispatcher)
        return EmptyCoroutineContext + testDispatcher + provider
    }

    @Test
    @ExperimentalCoroutinesApi
    fun advanceTimeIssueFixed() = runBlockingTest(contextWithProvider()) {
        delayOnProvidedMain()
        advanceTimeBy(1000)
    }

Thanks for the report and minimum repro! I'll have a fix PR'd shortly.

It should be fixed now in 1.0.0-beta02. Would you mind giving it a shot and confirming?

Thanks again!

Yep, perfect. Thanks for releasing a fix at warp speed ;-)

By the way: you only released beta02 for dispatcher-provider-test, right? At least my gradle complained about not finding dispatcher-provider with version beta02.

Thanks for checking it out!

I released both artifacts, and I'm able to import both of them now on my machine. I think someone at maven central just needed to flip their floppy disk over.

Yep, seemed to be a maven central problem, by now it succeeded.
Thanks again for your support.