Android JUnit本地测试-';未解析引用:test'; 预期

Android JUnit本地测试-';未解析引用:test'; 预期,android,kotlin,junit,junit4,android-testing,Android,Kotlin,Junit,Junit4,Android Testing,将诸如androidx.test:core:1.2.0,androidx.test.ext:truth:1.2.0,com.google.truth:truth:0.44等库导入名为ExampleUnitTest.kt的本地JUnit测试类 观察 错误 未解析引用:测试 实施 示例UnitTest.kt 解决方案 这似乎是记录在中的一个问题 在Codelab sample build.gradle中,这被称为已知问题 // Once https://issuetracker.google.com

将诸如
androidx.test:core:1.2.0
androidx.test.ext:truth:1.2.0
com.google.truth:truth:0.44
等库导入名为ExampleUnitTest.kt的本地JUnit测试类

观察 错误 未解析引用:测试

实施 示例UnitTest.kt

解决方案 这似乎是记录在中的一个问题

在Codelab sample build.gradle中,这被称为已知问题

// Once https://issuetracker.google.com/127986458 is fixed this can be testImplementation
implementation "androidx.test:core:$androidXTestCoreVersion"
我将应用程序的依赖项重构为
testImplementation
,而不是
androidTestImplementation

testImplementation 'androidx.test:core:1.2.0'
testImplementation 'androidx.test.ext:truth:1.2.0'
testImplementation 'com.google.truth:truth:0.44'

注意-谷歌文档应该更新以反映这个问题,因为它当前指示开发人员使用
androidTestImplementation
。我已经提交了一个文档问题来解决这个问题。

您是在指令测试(
androidTest/
)还是单元测试(
test/
)中使用这个问题,但可能您的Gradle dependency指令与测试类所在的位置不匹配。@Commonware,这在JUnit测试的'src/test'目录下。@Commonware,我用发布的解决方案解决了第一个问题。但是,现在当我尝试使用
InstrumentationRegistry.getInstrumentation().getTargetContext()
getApplicationContext()
检索应用程序上下文时,我收到一个错误java.lang.IllegalStateException:未注册检测!必须在注册检测下运行。。这是使用库
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.core.app.ApplicationProvider.getApplicationContext
.AFAIK,
ApplicationProvider
至少目前是用于插入仪器的测试的。我认为有一个计划将这些东西与基于Mockito的mock统一起来,作为氮项目的一部分进行单元测试,但我认为还没有准备好。那么
InstrumentationRegistry.getInstrumentation().getTargetContext()
呢?我已经读过这篇文章,它应该用于在JUnit测试中访问应用程序上下文。
testImplementation 'androidx.test:core:1.2.0'
testImplementation 'androidx.test.ext:truth:1.2.0'
testImplementation 'com.google.truth:truth:0.44'