I have a test for my ViewModel in android. everyth...
# coroutines
c
I have a test for my ViewModel in android. everything works fine. I had to add a
Copy code
closeableScope.launch {

}
and now that I did that, my test times out. if i remove the
blah.collectLatest {}
then it passes. Anyone have tips on what to do in this scenario. im still a rookie when it comes to testing, especially coroutines/flows
m
runTests
waits for all child jobs to finish. If nothing cancels the launched job and if the flow doesn't complete, then the job will keep running and the test will time out.
f
Pass the backgroundScope to the viewModel instead of the
runTest
one.
👍 1
m
I didn't know about that, seems useful
c
hm... let me try it out. i am injecting a closeableScope to my VM to make it testable and get around all of the Main.dispatcher stuff. but I typically pass in the runTest { coroutineContext } into the VM as the closeableScope
interesting. yeah that worked @franztesca!
Copy code
HomeViewModel(
    appStateHolder = fakeAppStateHolder,
    closeableScope = CloseableCoroutineScope(backgroundScope.coroutineContext),
p
For anyone reading this, make sure your test class only has one instance of TestScope. Using the top-level
runTest
function is totally fine, but if you do, make sure you don’t also call
val scope = TestScope()
anywhere in else in test file. If you need a reference to a TestScope, you can instantiate one yourself and instead use
fun myTest = testScope.runTest { }
instead of the top-level
runTest
function. https://slack-chats.kotlinlang.org/t/3157046/the-android-coroutine-testing-https-developer-android-com-ko
🤔 1