👋🏻 Hey guys, question regarding testing the coroutines.
Suppose I have a class like this:
Copy code
class Launcher(dispatcher: CoroutineDispatcher) {
private val scope = CoroutineScope(SupervisorJob() + dispatcher)
fun launchItem() {
scope.launch { /* Do my thing here */ }
}
}
I suppose the correct way to test this is to use
Dispatchers.setMain(myDispatchers)
in the
@Before
function and then use
runBlocking
in my test function, where I call
launcher.launchItem
, right?
Or how should I test a method that’s not
suspend
but launches a
coroutine
inside ?
j
Joffrey
11/25/2021, 3:23 PM
I usually allow to override the whole
coroutineContext
instead of just the dispatcher in this kind of classes. This way you can make the job a child of your test's
coroutineContext
. Otherwise
runBlocking
and the likes will not wait for your coroutine to finish.
d
Didier Villevalois
11/25/2021, 3:27 PM
The testing framework has been completely reworked in 1.6.0-RC. The explanations on how to proceed are very well detailed in the new README.