jean
12/23/2020, 1:09 PM@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?Tijl
12/23/2020, 1:34 PMCoroutineScope(coroutineDispatcher).launch {
blockingTask()
you create your own scope instead of using anything from the test packagejean
12/23/2020, 2:30 PMTijl
12/23/2020, 2:33 PMlaunch { blockingTask() }
from inside runBlockingTest
, maybe the dispatcher is also available from the rule or something. I don’t personally use this package much.