You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I have a class where I inject both a CoroutineScope (such as MainScope) and a background dispatcher (such as Dispatchers.Default). I have a method which launches a coroutine in the scope and then uses withContext to switch to the background dispatcher, where it calls delay().
class ClassUnderTest(private val mainScope: CoroutineScope, private val bgDispatcher: CoroutineDispatcher {
fun doSomething() {
mainScope.launch {
val data = withContext(bgDispatcher) {
delay(1000)
42
}
doSomethingWithData(data)
}
}
}
private val testBgDispatcher = TestCoroutineDispatcher()
private val testScope = TestCoroutineScope()
private lateinit var subject: ClassUnderTest
@BeforeEach
fun setUp() {
subject = ClassUnderTest(testScope, testBgDispatcher)
}
@Test
fun testSomething() {
subject.doSomething()
testScope.advanceUntilIdle()
}
When I try to test this function I get an UncompletedCoroutinesError because the delay() doesn't advance when I call testScope.advanceUntilIdle().
As a workaround I could call testDispatcher.advanceUntilIdle(). A better workaround is to pass my TestCoroutineDispatcher to the TestCoroutineScope's constructor:
private val testBgDispatcher = TestCoroutineDispatcher()
private val testScope = TestCoroutineScope(testBgDispatcher)
However, I think the best solution would be to expose the TestCoroutineScope's dispatcher, so I can retrieve it and inject it in my class.
I have a class where I inject both a CoroutineScope (such as
MainScope
) and a background dispatcher (such asDispatchers.Default
). I have a method which launches a coroutine in the scope and then useswithContext
to switch to the background dispatcher, where it callsdelay()
.When I try to test this function I get an
UncompletedCoroutinesError
because thedelay()
doesn't advance when I calltestScope.advanceUntilIdle()
.As a workaround I could call
testDispatcher.advanceUntilIdle()
. A better workaround is to pass my TestCoroutineDispatcher to the TestCoroutineScope's constructor:However, I think the best solution would be to expose the TestCoroutineScope's dispatcher, so I can retrieve it and inject it in my class.
The text was updated successfully, but these errors were encountered: