【问题标题】:Test Kotlin Coroutines with runBlockingTest{} failed使用 runBlockingTest{} 测试 Kotlin 协程失败
【发布时间】:2022-01-11 12:54:06
【问题描述】:

我创建了一个简单的 Micronaut Kotlin Coroutines 示例,希望使用 kotlin-corotines-test 编写测试。我在依赖项中添加了kotlin-corotines-test。

我尝试使用runBlockingTest,但以下测试(Kotest/FuncSpec)失败。

@Test
fun `test GET all posts endpoint`() = runBlockingTest {
    val response = client.exchange("/posts", Array<Post>::class.java).awaitSingle()

    response.status shouldBe HttpStatus.OK
    response.body()!!.map { it.title }.forAny {
        it shouldContain "Micronaut"
    }
}

并抛出这样的异常。

java.lang.IllegalStateException: This job has not completed yet
    at kotlinx.coroutines.JobSupport.getCompletionExceptionOrNull(JobSupport.kt:1190)
    at kotlinx.coroutines.test.TestBuildersKt.runBlockingTest(TestBuilders.kt:53)
    at kotlinx.coroutines.test.TestBuildersKt.runBlockingTest$default(TestBuilders.kt:45)
    at com.example.ApplicationTest.test GET posts endpoint(ApplicationTest.kt:30)

但如果在 fun body 中使用runBlocking,它会起作用。

@Test
fun `test GET all posts endpoint`() {
    runBlocking {
        val response = client.exchange("/posts", Array<Post>::class.java).awaitSingle()

        response.status shouldBe HttpStatus.OK
        response.body()!!.map { it.title }.forAny {
            it shouldContain "Micronaut"
        }
    }
}

更新:从 issue Kotlin/kotlinx.coroutines#1204 获取解决方案,将 kotlin 协程更新到 1.6.0-RC 以解决它,并使用 runTest 代替已弃用的 runBlockingTest。

【问题讨论】:

    标签: kotlin kotlin-coroutines kotest


    【解决方案1】:

    这是一个已知问题,您可以查看here。

    也只是在这里记录一下,解决方法很少:

    • 使用 InstantTaskExecutorRule
    @get:Rule
    val instantExecutorRule = InstantTaskExecutorRule()
    
    • 使用 runBlocking
    @Test
    fun test() = runBlocking {
        coroutineJob.join()
    }
    
    • 确保从测试调度程序实例调用
    coroutineRule.testDispatcher.runBlockingTest{...}
    

    【讨论】:

    • 我在这个示例项目中使用 Kotest。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-24
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    • 2022-07-05
    • 2020-04-12
    • 2018-05-13
    相关资源
    最近更新 更多