I'm not able to figure out how to test that a SharedFlow
with replay=0
emitted a value.
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.runBlocking
import org.junit.Test
class ShowcaseTest {
@Test
fun testIntSharedFlowFlow() {
val intSharedFlow = MutableSharedFlow<Int>()
runBlocking {
intSharedFlow.emit(1)
}
// Does not work as there is no buffer because MutableSharedFlow(replay=0)
assert(intSharedFlow.replayCache.first() == 1)
}
}
The shareIn function returns a SharedFlow , a hot flow that emits values to all consumers that collect from it.
MutableSharedFlow See the SharedFlow documentation for details on shared flows. MutableSharedFlow is a SharedFlow that also provides the abilities to emit a value, to tryEmit without suspension if possible, to track the subscriptionCount, and to resetReplayCache.
runBlockingTest This is similar to runBlocking but it will immediately progress past delays and into launch and async blocks. You can use this to write tests that execute in the presence of calls to delay without causing your test to take extra time.
You could use tryEmit() instead and verify the returned result
UPDATE:
Consider using Turbine For ex:
sharedFlow.test {
sharedFlow.emit(1)
assertEquals(expected = 1, expectItem())
cancelAndIgnoreRemainingEvents()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With