Control coroutine time instead of sleeping
runTest provides coroutine test support and a test scheduler. Delays using its test dispatcher can advance virtually, so tests need not wait for real seconds. Add kotlinx-coroutines-test aligned with your core coroutine dependency.
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
class AsyncTest {
@Test fun returnsAfterDelay() = runTest {
val result = async {
delay(1_000)
25
}
assertEquals(25, result.await())
}
}
Hard-coded production dispatchers can escape the scheduler and introduce real timing. Inject dispatchers or scopes where needed. Infinite background collectors should use backgroundScope or be explicitly cancelled rather than keeping the test alive forever.
Exercise
Test a cancelled operation and a failing child. Add a fake suspending loader and verify the caller does not return before required child work completes.
Check: passing under one scheduling order does not establish thread safety. Use these tests to validate lifetime and ordering contracts, then add appropriate concurrency tests when shared state exists.