Android Studio测试Room数据库出现Unresolved reference依赖错误求助
问题根因
- 依赖声明与测试文件存放目录不匹配:
src/test/为本地JVM单元测试目录,仅能读取testImplementation声明的依赖;你当前所有Android测试相关依赖均使用androidTestImplementation声明,该配置仅对src/androidTest/目录下的instrumented测试生效,因此src/test/下的测试代码找不到对应类。 - Room依赖版本冲突:同时引入了已废弃的
android.arch.persistence.room旧版本依赖和androidx.room新版本依赖,会引发类冲突。
解决步骤
方案1:保留测试文件在src/test/(本地JVM单元测试)
- 先删除dependencies块中两行过时的Room依赖:
// 删除这两行 implementation 'android.arch.persistence.room:runtime:1.0.0-alpha1' annotationProcessor 'android.arch.persistence.room:compiler:1.0.0-alpha1'
- 调整room-testing依赖版本与主Room依赖对齐,同时补充本地测试所需的依赖声明:
dependencies { // 原有依赖保持不变,新增以下testImplementation声明 testImplementation "androidx.test.ext:junit:1.1.2" testImplementation "androidx.test:core:1.2.0" testImplementation "androidx.test:runner:1.3.0" testImplementation "androidx.arch.core:core-testing:2.1.0" // room-testing版本和你主room的2.3.0对齐 testImplementation "androidx.room:room-testing:2.3.0" testImplementation "com.google.truth:truth:1.1.2" // 协程测试版本和你主协程的1.4.2对齐 testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.4.2" testImplementation "org.robolectric:robolectric:4.5.1" // 原有androidTestImplementation的room-testing也同步修改版本为2.3.0 androidTestImplementation "androidx.room:room-testing:2.3.0" }
- 同步Gradle配置后重新构建项目即可。
方案2:使用instrumented测试
直接将DatabaseTest.kt从src/test/java/com/example/plantmanagement/移动到src/androidTest/java/com/example/plantmanagement/目录下,同步Gradle后连接模拟器/真机即可运行测试。
额外检查项
确认测试类的导入语句正确:
AndroidJUnit4:import androidx.test.ext.junit.runners.AndroidJUnit4ApplicationProvider:import androidx.test.core.app.ApplicationProviderassertThat:import com.google.common.truth.Truth.assertThat
内容的提问来源于stack exchange,提问作者Edita Komarova
相关产品推荐
相关产品推荐

