After updating the library turbine to version 1.0.0 I get following error.
java.lang.AssertionError: Turbine can only collect flows within a TurbineContext. Wrap with turbineScope { .. }
TL;TR
Wrap your test in trubineScope { }
. For example:
@Test
fun `Test example`() = runTest {
turbineScope { // <-- Add this
val turbine1 = flowOf(1).testIn(backgroundScope)
val turbine2 = flowOf(2).testIn(backgroundScope)
assertEquals(1, turbine1.awaitItem())
assertEquals(2, turbine2.awaitItem())
turbine1.awaitComplete()
turbine2.awaitComplete()
}
}
Changed API
With version 1.0.0 they introduced a new DSL function named turbineScope
. This function is now required for all testIn(...)
calls.
Confusing scopes
My first attempt was to replace the runTest
with turbineScope
and call testIn(this)
. But this is wrong. Your don’t need to change your testIn(background)
call, and always need wrap with runTest
to run suspend function testing.
Update your code
For get your tests run again, you need to wrap all tests that are using testIn(..)
with turbineScope
.
As mentioned you also need the runTest
test scope. Following full example will work with new updated turbine library:
package de.fabiankeunecke.codewerkstatt
import app.cash.turbine.turbineScope
import junit.framework.TestCase.assertEquals
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.runTest
import org.junit.Test
class SampleTest {
@Test
fun `Test testIn`() = runTest {
turbineScope {
val turbine1 = flowOf(1).testIn(backgroundScope)
val turbine2 = flowOf(2).testIn(backgroundScope)
assertEquals(1, turbine1.awaitItem())
assertEquals(2, turbine2.awaitItem())
turbine1.awaitComplete()
turbine2.awaitComplete()
}
}
}
That’s it!