Greg Rynkowski
06/03/2022, 6:05 PMrunTest
.
Have a look at the two tests below. The first uses runBlockingTest, the other runTest.
@Test
fun `test shared flow with deferred`() = runBlockingTest {
val sharedFlow = MutableSharedFlow<Int>(replay = 0)
val deferred = async { sharedFlow.first() }
sharedFlow.emit(1)
assertEquals(1, deferred.await())
}
@Test
fun `test shared flow with deferred - runTest`() = runTest {
val sharedFlow = MutableSharedFlow<Int>(replay = 0)
val deferred = async { sharedFlow.first() }
sharedFlow.emit(1)
assertEquals(1, deferred.await())
}
Why the second one never finish?ephemient
06/03/2022, 6:18 PMasync {}
will not have run yet in `runTest`; use runCurrent()
between it and .emit()
or async(start = CoroutineStart.UNDISPATCHED)
may work as wellAlbert Chang
06/04/2022, 1:50 AMrunTest(UnconfinedTestDispatcher())
.
https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-test/MIGRATION.md#replace-runblockingtest-with-runtestunconfinedtestdispatcher
https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-test/kotlinx.coroutines.test/-unconfined-test-dispatcher.html