Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test that a MutableSharedFlow<T>(replay=0) has emitted a value?

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)
    }
}
like image 671
Víctor Albertos Avatar asked Dec 10 '20 13:12

Víctor Albertos


People also ask

Is SharedFlow hot?

The shareIn function returns a SharedFlow , a hot flow that emits values to all consumers that collect from it.

What is MutableSharedFlow?

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.

What is runBlockingTest?

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.


1 Answers

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()

}
like image 90
Róbert Nagy Avatar answered Sep 18 '22 13:09

Róbert Nagy