How do I unit test a singleton launching a never e...
# getting-started
d
How do I unit test a singleton launching a never ending coroutine?
Copy code
class 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
Copy code
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
Copy code
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
Copy code
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?