https://kotlinlang.org logo
#flow
Title
# flow
j

Jeziel Lago

04/13/2021, 2:46 PM
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

ephemient

04/13/2021, 4:25 PM
.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

Javier

04/13/2021, 4:36 PM
Try turbine library
j

Jeziel Lago

04/13/2021, 5:02 PM
@ephemient
first()
not works.
e

ephemient

04/13/2021, 5:03 PM
@Jeziel Lago you're sure you added
replay = 1
as well? the default
replay = 0
doesn't work with this
j

Jeziel Lago

04/13/2021, 5:07 PM
Using
replay = 1
it works, but I need
replay = 0
.
j

Javier

04/13/2021, 5:10 PM
maybe toList().first()?
j

Jeziel Lago

04/13/2021, 5:12 PM
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

Javier

04/13/2021, 5:13 PM
Really I think we need a coroutines test framework
e

ephemient

04/13/2021, 6:09 PM
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

Jeziel Lago

04/13/2021, 6:36 PM
Turbine works well here. Thanks @ephemient
@elizarov any plans for including something like Turbine (for MutableSharedFlow) in Kotlin Coroutine Test library?
e

elizarov

04/13/2021, 9:08 PM
What's wrong with Turbine that you want an alternative?
j

Jeziel Lago

04/13/2021, 9:50 PM
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
126 Views