What is the right way to testing a `MutableSharedF...
# flow
j
What is the right way to testing a
MutableSharedFlow
?
Copy code
@Test
    fun testIntSharedFlow() = runBlockingTest {
        val intSharedFlow = MutableSharedFlow<Int>()

        intSharedFlow.emit(5)

        assertEquals(5, intSharedFlow.single())
    }
This code results
java.lang.IllegalStateException: This job has not completed yet
e
.single()
can't work on a SharedFlow, since it never terminates
Copy code
val intSharedFlow = MutableSharedFlow<Int>(replay = 1)
intSharedFlow.emit(5)
assertEquals(5, intSharedFlow.first())
I'd expect that to work
j
Try turbine library
j
@ephemient
first()
not works.
e
@Jeziel Lago you're sure you added
replay = 1
as well? the default
replay = 0
doesn't work with this
j
Using
replay = 1
it works, but I need
replay = 0
.
j
maybe toList().first()?
j
toList().first()
not works too. Turbine library seems a good option. Thanks @Javier I’m disappointed with the Kotlin test library does not work with this use case.
j
Really I think we need a coroutines test framework
e
you have a race condition with
replay = 0
- need to subscribe to the flow before emitting
with Turbine you could probably do something like
Copy code
val intSharedFlow = MutableSharedFlow<Int>()
intSharedFlow.test {
    intSharedFlow.emit(5)
    assertEquals(5, expectItem())
}
👍 1
j
Turbine works well here. Thanks @ephemient
@elizarov any plans for including something like Turbine (for MutableSharedFlow) in Kotlin Coroutine Test library?
e
What's wrong with Turbine that you want an alternative?
j
For me, Turbine is an excellent library, and I think nothing is wrong with it. But we have a library to deal with test kotlinx-coroutines-test, which has a goal:
provides testing utilities for effectively testing coroutines
, that not help us so much (testing MutableSharedFlow as an example). IMHO, is very important to provide utilities (or ways and to show how) to test new components when releasing them to the community. Thanks all for helping me!
👍 2
133 Views