https://kotlinlang.org logo
#coroutines
Title
# coroutines
j

jean

12/23/2020, 1:09 PM
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

Tijl

12/23/2020, 1:34 PM
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

jean

12/23/2020, 2:30 PM
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

Tijl

12/23/2020, 2:33 PM
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.
2 Views