JUnit本地测试 - '未解决的引用:test'

12

预期结果

在一个名为ExampleUnitTest.kt本地JUnit测试类中导入库,如androidx.test:core:1.2.0androidx.test.ext:truth:1.2.0com.google.truth:truth:0.44等。

观察到结果

错误信息

未解决的引用: test

实现方式

ExampleUnitTest.kt

import androidx.test.core.app.ApplicationProvider.getApplicationContext
import com.google.common.truth.Truth.assertThat

你是在使用插桩测试(androidTest/)还是单元测试(test/)?看起来你已经导入正确的包,但是也许你的Gradle依赖指令与测试类所在位置不匹配。 - CommonsWare
@CommonsWare,这是用于JUnit测试的“src/test”目录下的内容。 - AdamHurwitz
@CommonsWare,我已经修复了我发布的解决方案中的第一个问题。但是,现在当我尝试检索app上下文时,使用InstrumentationRegistry.getInstrumentation().getTargetContext()getApplicationContext(),我收到错误消息_java.lang.IllegalStateException: No instrumentation registered! Must run under a registering instrumentation._。这是使用库import androidx.test.platform.app.InstrumentationRegistryimport androidx.test.core.app.ApplicationProvider.getApplicationContext - AdamHurwitz
据我所知,ApplicationProvider 是用于仪器化测试的,至少目前是这样。我认为计划将其与基于 Mockito 的模拟一起统一用于单元测试,作为氮项目的一部分,但我认为这还没有准备好。 - CommonsWare
InstrumentationRegistry.getInstrumentation().getTargetContext()怎么样?我读到这应该在JUnit测试中用于访问app上下文这里 - AdamHurwitz
@CommonsWare,我已经通过Twitter向'@AndroidDev'发送了一条关于文档的注释 - AdamHurwitz
1个回答

29

解决方法

这似乎是在Android测试Codelab示例应用程序文档中记录的问题。

在Codelab示例build.gradle中,这被称为已知问题。

// Once https://issuetracker.google.com/127986458 is fixed this can be testImplementation
implementation "androidx.test:core:$androidXTestCoreVersion"

我将应用程序的依赖项从 androidTestImplementation 重构为 testImplementation

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

Note - 谷歌文档 Set up project for AndroidX Test 需要更新以反映这个问题,因为它目前指导开发者使用androidTestImplementation。我已经提交了一个文档问题来解决这个问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接