Would you please help me with the following? I wan...
# coroutines
e
Would you please help me with the following? I want to test that the buffer size of my
MutableSharedFlow<T>(replay = 0, extraBufferCapacity = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)
equals
1
(in reality it's variable). I can't figure out how to get this working in a unit test: every time I emit something it is immediately collected (I use Turbine to
test
the flow). I basically want to emit 2 items and verify that only the last one is collected, the oldest is dropped.
­čĹŹ 1
Maybe it's related to the unconfined dispatcher used by Turbine: I cannot pause that dispatcher, because it's not my test dispatcher?
This works:
Copy code
@Test
    fun test() = testCoroutineDispatcher.runBlockingTest {
        val flow = MutableSharedFlow<Int>(
            replay = 0,
            extraBufferCapacity = 1,
            BufferOverflow.DROP_OLDEST
        )

        val emissions = mutableListOf<Int>()

        val subscription = flow.onEach { emissions += it }.launchIn(this)

        pauseDispatcher()
        flow.tryEmit(1)
        flow.tryEmit(2)
        resumeDispatcher()

        assertEquals(2, emissions.single())

        subscription.cancel()
    }
But it's not very pretty, because it's somewhat imperative
Using Turbine I'd like to do:
Copy code
@Test
    fun test() = testCoroutineDispatcher.runBlockingTest {
        val flow = MutableSharedFlow<Int>(
            replay = 0,
            extraBufferCapacity = 1,
            BufferOverflow.DROP_OLDEST
        )

        flow.test {
            pauseDispatcher()
            flow.tryEmit(1)
            flow.tryEmit(2)
            resumeDispatcher()

            assertEquals(2, expectItem())
            expectNoEvents()
        }
    }
but that fails with:
Copy code
java.lang.AssertionError: 
Expected :2
Actual   :1
Likely because of what I said: Turbine collects on the unconfined dispatcher, not my test coroutine dispatcher