I’m having trouble to really understand how one sh...
# coroutines
j
I’m having trouble to really understand how one should test coroutines/flow. I have this dummy code :
Copy code
@get:Rule
val coroutineTestRule = CoroutineTestRule()

class StateFlowTestClass(
    coroutineDispatcher: CoroutineDispatcher = Dispatchers.Main
) {
    private val _state = MutableStateFlow(0)
    val state: StateFlow<Int> = _state

    init {
        CoroutineScope(coroutineDispatcher).launch {
            blockingTask()
        }
    }

    private suspend fun blockingTask() {
        delay(10.seconds)
        _state.value = 1
    }
}

@Test
fun `test on StateFlow`() = coroutineTestRule.runBlockingTest {
    advanceTimeBy(11.seconds.toLongMilliseconds())
    val value = StateFlowTestClass(TestCoroutineDispatcher()).state.value
    Assert.assertEquals(1, value)
}
when I run test on StateFlow I get the following error :
java.lang.AssertionError: Expected:1, Actual:0
. How am I suppose to fix this? How about when there is no delay but just a bunch of code taking time to execute, is there a way to wait it to be done?
t
Copy code
CoroutineScope(coroutineDispatcher).launch {
            blockingTask()
you create your own scope instead of using anything from the test package
so advancing time does not work, it only works from the test scope
j
What am I suppose to use then? I don’t know how to use the test package when running the test or using another scope/context whatever when running the code “normally”
t
you can do your
launch { blockingTask() }
from inside
runBlockingTest
, maybe the dispatcher is also available from the rule or something. I don’t personally use this package much.