I'd like to Unit Test the following class : ``` cl...
# coroutines
t
I'd like to Unit Test the following class :
Copy code
class MyClass(private val scope: CoroutineScope) {
     // launches new coroutines in the passed scope 
}
Some of my test scenarios requires that the passed
CoroutineScope
be cancelled. How would you write such test with
runBlockingTest
?
e
Could you create a dummy class which implements CoroutineScope that just creates a job for its context and immediately cancels it? You may be able to attach its job as a child of the coroutine scope of runBlockingTest
t
I ended up writing this function :
Copy code
fun TestCoroutineScope.runInScope(block: suspend CoroutineScope.() -> Unit) {
    val job = launch(block = block)
    advanceUntilIdle()
    job.cancel()
}
The passed
block
is executing eagerly due to
runBlockingTest
, advances until idle then cancel the scope. This should be enough to simulate the lifecycle of a child
CoroutineScope
. I wonder if such thing is possible with existing constructs, for example
coroutineScope { ...}
.