Let's say I have Worker class and I want to do long running tasks in the background until user stops it or it is cancelled. It changes state of the class while doing the work and I want to write tests how work progresses with each loop. For this example I want to check loopCounter value after first yield(). How can I achieve that? Or maybe I should use coroutines differently here?
class Worker(
private val coroutineContext: CoroutineContext = Dispatchers.Default,
) {
var loopCounter: Long = 0
private set
private var job: Job? = null
fun start() {
if (job?.isActive == true) return
job = CoroutineScope(coroutineContext).launch {
while (isActive && loopCounter < 100) {
loopCounter++
doWork()
yield()
}
}
}
fun stop() {
job?.cancel()
}
private suspend fun doWork() {
// Your long-running task logic
println("Loop $loopCounter running on thread: ${Thread.currentThread().name}")
}
}
Example test:
@Test
fun `loopCounter increments with yield`() = runTest {
val dispatcher = StandardTestDispatcher(testScheduler)
val worker = Worker(dispatcher)
worker.start()
testScheduler.runCurrent()
assertTrue(worker.loopCounter == 1L)
}