使用runBlockingTest测试Kotlin协程报This job has not completed yet错误如何解决
问题复现与解决方案
问题背景
在Micronaut框架下开发Kotlin协程项目,引入kotlinx-coroutines-test库编写接口测试用例时,使用runBlockingTest封装测试逻辑会执行失败。
报错测试代码
@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)
临时可用写法
将runBlockingTest替换为普通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" } } }
最终解决方案
该问题是kotlinx-coroutines-test旧版本的已知缺陷,修复方案如下:
- 将项目的Kotlin协程依赖版本升级到1.6.0-RC及以上
- 使用官方新提供的
runTest方法替代已废弃的runBlockingTest编写协程测试用例,即可彻底解决该错误
内容的提问来源于stack exchange,提问作者Hantsy
相关产品推荐
相关产品推荐

