Colton Idle
07/25/2023, 11:31 PM@Test
fun `assert foo`() = runTest{
val bar = Bar(coroutineContext)
bar.sync()
assertThat(bar.state.sync).isEqualTo("bla")
}
Bar has sync defined as
fun syncConfig() {
passedInScope.launch {
state = "bla"
}
}
so. basically. can i do something like this?
@Test
fun `assert foo`() = runTest{
val bar = Bar(coroutineContext)
bar.sync()
coroutineContext.waitTillAllWorkIsDone() <==== the additional line
assertThat(bar.state.sync).isEqualTo("bla")
}
Francesc
07/26/2023, 12:53 AMsync
to be a suspend
function (that'd be my preferred way, having methods that launch and forget lead to issues)
• have the passedInScope
provided to whatever class includes syncConfig
and in tests pass a test scope, either coroutineContext
from runTest
, backgroundScope
from runTest
or some other scope you can controlFrancesc
07/26/2023, 12:56 AMjob
from syncConfig
and then join
thatAlbert Chang
07/26/2023, 10:16 AMtestScheduler.advanceUntilIdle()
after bar.sync()
should make it work I believe.Albert Chang
07/26/2023, 10:19 AMlaunch
and async
calls to be executed automatically, you can also use runTest(UnconfinedTestDispatcher())
.Colton Idle
07/26/2023, 1:01 PMadvanceUntilIdle
worked!Colton Idle
07/26/2023, 1:01 PMColton Idle
07/26/2023, 1:02 PM• refactorI think I'd like to do that, but my code above is actually a viewModel. So the videwModel has a function that fires a call and then updates some compose snapshot state. so all of the recs I've seen before say that not exposing a suspend fun in ViewModel is a good idea.to be async
function (that'd be my preferred way, having methods that launch and forget lead to issues)suspend
Colton Idle
07/26/2023, 1:04 PM• have theYeah, that's what I'm doing now. PassedInScope == coroutineContext fromprovided to whatever class includespassedInScope
and in tests pass a test scope, eithersyncConfig
fromcoroutineContext
,runTest
frombackgroundScope
or some other scope you can controlrunTest
val bar = Bar(coroutineContext)
sorry that I didn't make that clear enough. 🤦Colton Idle
07/26/2023, 1:04 PMIf you would like@Albert Chang hm. I don't think I follow.andlaunch
calls to be executed automatically, you can also useasync
.runTest(UnconfinedTestDispatcher())
Albert Chang
07/27/2023, 9:16 AMColton Idle
07/27/2023, 2:13 PMColton Idle
07/28/2023, 2:21 PM