Test suspended MutableStateFlow
consumer
#89
-
I want to test a MutableStateFlow scenario. Let’s say there’s a MutableStateFlow called visible. I started collecting updates from this Flow in some Activity Lifecycle lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
visible.collect { println(it) }
}
} Now, there’s some Handler living the Application Lifecycle and this MutableStateFlow 'visible' is actually maintained by this component (Singleton Scoped). Consider the emissions
AFAIK, the activity should only receive Tried this unit test. Didn't work @Test
fun testMutableStateFlow() {
val mainDispatcher = TestCoroutineDispatcher()
val ioDispatcher = TestCoroutineDispatcher()
val actionsFlow = MutableStateFlow(0)
mainDispatcher.runBlockingTest {
actionsFlow.test {
expectItem() // default
pauseDispatcher()
launch(ioDispatcher) {
actionsFlow.emit(1)
actionsFlow.emit(2)
}
resumeDispatcher()
assertEquals(expectItem(), 2)
}
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
If you are testing the You don't need to test that You can test the |
Beta Was this translation helpful? Give feedback.
If you are testing the
visible
flow then you can only test the values of the items which are emitted in reaction to events (presumably the thing which triggers the value to change).You don't need to test that
MutableStateFlow
keeps the latest value / replays the latest value to collectors because you didn't write that class and you can trust it to behave as documented.You can test the
repeatOnLifecycle
part of the codebase but only if you have some kind of indirection where you can intercept the values which it collects and you would not actually use Turbine for that because of the fact that it manages the collection of the flow. Instead you would set up a fake lifecycle, emit a value, …