Hello ! Is it possible to unit test for job cancel...
# coroutines
n
Hello ! Is it possible to unit test for job cancellation for a class like below ?
Copy code
class Sample(private val scope: CoroutineScope) {
    
    private var currentJob: Job? = null
    
    fun doSomeAsyncWork() {
        currentJob?.cancel() // how to test this line ?
        currentJob = scope.launch { 
            delay(5000)
        }
    }
}
m
In the example shown the job does nothing, so you cannot test the method at all. How to test it would depend on what it is actually doing. If it calls a method in a injectable dependency, you could replace the dependency with some sort of fake that waits for cancelation on the first call and works on the second call. Use a unconfined type of scope so the launch happens immediately. Then call
doSomeAsyncWork
twice and see that the first job was canceled and the second job was started.
r
Just to add to @mkrussel’s answer, one of the key principles of testing is to test behaviours and not implementation details.
Here the fact that
doSomeAsyncWork
is creating the job at all is an implementation detail
You need to work out how that should affect its result or collaborators and test that which will indirectly test the cancellation behaviour
n
Thanks for your help. I thought I could use the coroutine API directly without the need of an abstraction over it.
I successfully tested everything but the cancellation.