kotlin-coroutineskotlintestkotest

Kotest and kotlinx-coroutines-test Integration


I use the Funspec testing style in kotest and I get a coroutineScope injected automatically by the framework as shown below.

class MyTestSpec: FunSpec() {
    init {
        test("test event loop") {
           mySuspendedFunction() // a coroutineScope is already injected by the test framework here     
        }
    }
}

How can I configure the Kotest framework to use an instance of kotlinx.coroutines.test.TestCoroutineScope instead of a kotlinx.coroutines.CoroutineScope in my tests? or is there a reason why this wouldn't make sense?


Solution

  • Create a test listener like this:

    class MainCoroutineListener(
        val testDispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()
    
    ) : TestListener {
        override suspend fun beforeSpec(spec: Spec) {
            Dispatchers.setMain(testDispatcher)
        }
    
        override suspend fun afterSpec(spec: Spec) {
            Dispatchers.resetMain()
            testDispatcher.cleanupTestCoroutines()
        }
    }
    

    Then use it in your test like this

    class MyTest : FunSpec({
        listeners(MainCoroutineListener())
        tests...
    })