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)
    }

0

Your Reply

By clicking “Post Your Reply”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.