Turbain and CoroutineTest with delay throws TimeoutCancellationException

Viewed 527

I am trying to test a flow with a delay by using Turbain and CoroutineTest library. Does anybody know What I am missing here?

    @Test
    fun test(){
        val flow = flow<Int> {
            emit(1)
            delay(1000)
            emit(2)
        }

        runBlockingTest {
            flow.test(Duration.INFINITE) {
                expectItem()
                expectItem()
                expectComplete()
            }
        }
    }

Here is the error I am getting.

kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 9223372036854775807 ms
1 Answers

use cancel() instead of cancelAndIgnoreRemainingEvents() to Cancel collecting events from the source Flow and ignore any events which have already been received. Calling this function will exit the test block. for more info check here

        @Test
        fun test(){
            val flow = flow<Int> {
                emit(1)
                delay(1000)
                emit(2)
            }
    
            runBlockingTest {
                flow.test(Duration.INFINITE) {
                    expectItem()
                  // verify using Assertions or whatever you want
                    cancel() //to cancel the flow
                }
            }
Related