Kotest and kotlinx-coroutines-test Integration

1.9k Views Asked by At

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?

2

There are 2 best solutions below

2
Tord Jon On BEST ANSWER

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...
})
0
Emil Kantis On

Since Kotest 5.0, there is built-in support for TestCoroutineDispatcher. See here

Simply:

class MyTest : FunSpec(
  {
    test("do your thing").config(testCoroutineDispatcher = true) { 
    }
  }
)