Patrick Ramsey
08/25/2021, 9:33 PM@Test fun `some particular invariant holds true`() = runBlockingTest {
coEvery { someSuspendingFunction() } coAnswers {
val dispatcher = coroutineContext[CoroutineDispatcher]
....
}
....
}
No matter which CoroutineDispatcher someSuspendingFunction() was called on, dispatcher
in this code seems to end up being the test dispatcher created by runBlockingTest.
If, however, I structure it like this:
private suspend fun mockImplementation() {
val dispatcher = coroutineContext[CoroutineDispatcher]
}
@Test fun `some particular invariant holds true`() = runBlockingTest {
coEvery { someSuspendingFunction() } coAnswers {
mockImplementation()
}
}
dispatcher
(in mockImplementation()) matches the dispatcher that someSuspendingFunction() was called on.
IE… it looks an awful like the coAnswers block is running on that dispatcher, but coroutineContext
specifically inside that block is reporting something different. Put differently --- coroutineContext seems to be returning the context from the enclosing lexical scope, rather than the context of the actual running coroutine.
Is that expected?@Test fun `some particular invariant holds true`() {
coEvery { someSuspendingFunction() } coAnswers {
val dispatcher = coroutineContext[CoroutineDispatcher]
...
}
runBlockingTest {
... rest of the test body ...
}
}
fixes the test.