This page shows some general techniques. In short, run with enabled assertions (-ea JVM flag).
kotlinx-coroutines-debug module is specifically designed for what its name says. This is how I use it in unit tests;
runBlocking {
DebugProbes.install()
val deferred = async { methodUnderTest() }
delay(3000)
DebugProbes.dumpCoroutines()
println("\nDumping only deferred")
DebugProbes.printJob(deferred)
DebugProbes.uninstall()
cleanup()
}
There’s a JUnit4 rule to reduce the boilerplate, but you shouldn’t be using JUnit4 in late 2020.
Also, Kotlin 1.4.0-RC and later has support for debugging Coroutines from inside the IDE, but just like everything new from JetBrains, I found it half-baked and not always showing suspended coroutines; kotlinx-coroutines-debug works better.
https://blog.jetbrains.com/kotlin/2020/07/kotlin-1-4-rc-debugging-coroutines/
Edit Oct 2020:
I created a JUnit 5 Extension that can dump coroutines on timeout.
https://github.com/asarkar/coroutines-test