Daniele Segato
12/23/2020, 1:15 PMclass MySingleton(private val scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)) {
init {
scope.launch {
neverEndingCoroutineHere()
}
}
}
The singleton already take a parameter for launching stuff in a scope.
When I test I give it the TestCouroutineScope
created by runBlockingTest
so tests fails with
kotlinx.coroutines.test.UncompletedCoroutinesError: Test finished with active jobs: ["coroutine#63":StandaloneCoroutine{Active}@1cec6f46]
I do not want to add a destroy()
function in my singleton, it makes no sense other than for testing.
And I don't want to cancel the TestCouroutineScope
either cause that check for unfinished jobs is actually very usuful.
My solution for now is to duplicate the scope in my singleton
class MySingleton(
private val scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
private val permanentScope: CoroutineScope = scope
) {
init {
permanentScope.launch {
neverEndingCoroutineHere()
}
}
}
and from my tests I give
permanentScope = CoroutineScope(SupervisorJob() + TestCoroutineDispatcher())
and cancel that in @After
which means never ending jobs like the one above run outside of the TestCoroutineScope
Is there a better way?