rogue-one
rogue-one

Reputation: 11577

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?

Upvotes: 3

Views: 2385

Answers (2)

Tord Jon
Tord Jon

Reputation: 46

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

Upvotes: 3

Emil Kantis
Emil Kantis

Reputation: 1114

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

Simply:

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

Upvotes: 4

Related Questions