Kotest 与 kotlinx-coroutines-test 集成

Kotest and kotlinx-coroutines-test Integration

我在 kotest 中使用了 Funspec 测试风格,我得到了一个由框架自动注入的 coroutineScope,如下所示。

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

如何配置 Kotest 框架以在我的测试中使用 kotlinx.coroutines.test.TestCoroutineScope 而不是 kotlinx.coroutines.CoroutineScope 的实例?还是这没有意义?

像这样创建一个测试监听器:

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

然后像这样在你的测试中使用它

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

从 Kotest 5.0 开始,内置了对 TestCoroutineDispatcher 的支持。参见 here

简单地说:

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