【问题标题】:Kotest and kotlinx-coroutines-test IntegrationKotest 和 kotlinx-coroutines-test 集成
【发布时间】:2021-11-23 18:33:28
【问题描述】:

我在 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?还是有什么理由让这没有意义?

【问题讨论】:

    标签: kotlin-coroutines kotlintest kotest


    【解决方案1】:

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

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

    【讨论】:

    • 感谢在每个规范之后必须重置调度程序的任何原因?我不能保持原样,因为我希望所有测试都使用 TestCoroutineScope 而不是普通的..
    • 监听器将在每个规范之前运行,因此您只需要应用一次监听器。
    【解决方案2】:

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

    简单地说:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-03
      • 1970-01-01
      • 2018-07-15
      • 2021-03-08
      • 2019-10-22
      • 2020-03-20
      • 2021-01-26
      • 1970-01-01
      相关资源
      最近更新 更多