迁移Kotlin Coroutines Test 1.6.x时基础测试报错:NoSuchMethodError
问题
迁移至kotlin coroutines test 1.6.x版本后,编写的基础测试用例执行失败:
import kotlinx.coroutines.test.runTest import org.junit.Test class HouseDaoTest { @Test fun insertAndGetHouseFromDb_success() = runTest { assert(1 == 1) assert(2 == 2) } }
报错信息:
No virtual method find(Lkotlin/jvm/functions/Function1;)Lkotlinx/coroutines/internal/ThreadSafeHeapNode; in class Lkotlinx/coroutines/internal/ThreadSafeHeap; or its super classes (declaration of 'kotlinx.coroutines.internal.ThreadSafeHeap' appears in /data/app/~~rVhSG062Jzg60YKAgWe6uQ==/my.packagename.test-Up28py4pbfA6CKyThEVObA==/base.apk)
已尝试降级至1.6.0版本无效,且已在官方仓库提交Issue。
解决方案
这个错误本质是kotlinx-coroutines-test与kotlinx-coroutines-core依赖版本不匹配:ThreadSafeHeap类来自coroutines-core库,而test库调用了该类中不存在的方法,说明两个库版本不一致。
强制统一所有kotlinx-coroutines相关依赖的版本:
在根项目的build.gradle(或build.gradle.kts)中统一版本配置:// Groovy语法 ext { coroutinesVersion = "1.6.4" // 选择1.6.x系列的稳定版本 } dependencies { implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutinesVersion" testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutinesVersion" // 其他coroutines相关依赖也使用同一版本 }// Kotlin DSL语法 val coroutinesVersion = "1.6.4" dependencies { implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutinesVersion") testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutinesVersion") }检查依赖树并排除冲突版本:
执行命令查看项目依赖树,定位引入旧版coroutines-core的第三方依赖:./gradlew app:dependencies找到冲突依赖后,添加排除配置:
// Groovy语法 implementation("第三方库坐标") { exclude group: 'org.jetbrains.kotlinx', module: 'kotlinx-coroutines-core' }// Kotlin DSL语法 implementation("第三方库坐标") { exclude(group = "org.jetbrains.kotlinx", module = "kotlinx-coroutines-core") }清理缓存并重建项目:
执行以下命令清除gradle缓存并重新构建:./gradlew clean build --refresh-dependencies
内容的提问来源于stack exchange,提问作者muetzenflo
相关产品推荐
相关产品推荐

