voben
12/05/2019, 11:09 PMIllegalStateException: This job has not completed yet
. I have a channel in my viewmodel which I expose as a flow
ViewModel
private val _channel = BroadcastChannel<Boolean>(1)
val myFlow = _channel.asFlow()
fun sendToChannel() {
viewModelScope.launch {
_channel.send(true)
}
}
And in my activity, I collect the flow
lifecycleScope.launch {
myFlow.collect { println(it) }
}
My Test
@Test
fun `myTest`() = runBlockingTest {
viewModel.myFlow.collect { myVal ->
assertTrue(myVal)
}
viewModel.sendToChannel()
}
How do I ensure the assertion is called. Or what’s a better way of testing this?octylFractal
12/05/2019, 11:20 PMvoben
12/05/2019, 11:53 PMstreetsofboston
12/05/2019, 11:55 PMrunBlockingTest
provides a TestCoroutineScope that dispatches on a TestCoroutineDispatcher.
Your viewModelScope
uses the Dispatchers.Main. This mismatch may be the problem, where sendToChannel really never winds up calling _channel.send()
.streetsofboston
12/05/2019, 11:58 PMvoben
12/06/2019, 12:18 AM@get:Rule
var coroutineRule = MainCoroutineRule()
@Test
fun myTest() = coroutineRule.runBlockingTest {}
https://gist.githubusercontent.com/manuelvicnt/049ce057fa6b5e5c785ec9fff7c22a7c/raw/b668143cbc1a8d52ef7267796b8a787165497702/CoroutinesTestRule.ktstreetsofboston
12/06/2019, 12:22 AMcollect
suspends and you never get to call viewModel.sendToChannel().streetsofboston
12/06/2019, 12:24 AMviewModel.myFlow.collect {...}
inside a launch
....voben
12/06/2019, 12:53 AMlaunch
it throws an UncompletedCoroutinesError: Test finished with active jobs
. I assume this is because the flow is still open to collecting. Do I then need to call cancel inside the of launch? because that seems seems a little flaky to me but the test passes. Here’s what I have so far
@Test
fun `myTest`() = coroutineRule.runBlockingTest {
launch {
viewModel.myFlow.collect { myVal ->
assertTrue(myVal)
cancel()
}
}
viewModel.sendToChannel()
}
voben
12/06/2019, 8:18 AM.take(n).toList()
rather than collect
. I think this might currently be the best way to test flow according to Manuel https://stackoverflow.com/a/58611767/5067435tseisel
12/06/2019, 8:20 AMFlow.test
operator. This might help you : https://kotlinlang.slack.com/archives/C1CFAFJSK/p1575206282080900