首页 > 解决方案 > Kotest 和 kotlinx-coroutines-test 集成

问题描述

我在 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而不是 a kotlinx.coroutines.CoroutineScope?或者有没有理由为什么这没有意义?

标签: kotlin-coroutineskotlintestkotest

解决方案


从 Kotest 5.0 开始,内置了对TestCoroutineDispatcher. 看这里

简单地:

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

推荐阅读