我创建了一个简单的 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)
但如果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"
}
}
}
更新:从问题Kotlin/kotlinx.coroutines#1204获取解决方案,将 kotlin 协程更新到 1.6.0-RC 以解决它,并使用runTest
而不是弃用的runBlockingTest
.