【问题标题】:Unresolved androidx classes for writing unit tests用于编写单元测试的未解决的 androidx 类
【发布时间】:2019-08-27 11:36:40
【问题描述】:

我正在尝试编写我的第一个测试,但在找出正确的依赖项以使一切正常运行时遇到问题。这是我的测试课

class EmployeeDatabaseTest {
    private lateinit var employeeDao: EmployeeDAO

    @Before
    fun setup() {
        EmployeeDatabase.TEST_MODE = true
        employeeDao = EmployeeDatabase.getDatabase(??).employeeDao()
    }

    @Test
    fun should_Insert_Employee_Item() {
        val employee = Employee("xx", "xx", 31, Gender.MALE)
        employee.id = 1
        runBlocking {  employeeDao.addNewEmployee(employee) }
        val employeeTest = runBlocking {  getValue(employeeDao.getEmployeeById(employee.id!!)) }
        Assert.assertEquals(employee.name, employeeTest.name)
    }
}

通常我会通过InstrumentationRegistry.getContext()... 获取上下文,但InstrumentationRegistry 无法解析。它也无法解析getValue(..) 方法。我是测试新手,但我敢打赌是有依赖关系的。这是我的build.gradle

dependencies {
   ...
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test:rules:1.2.0'
    androidTestImplementation 'org.hamcrest:hamcrest-library:1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'
    androidTestImplementation 'androidx.test:core:1.2.0'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
}

defaultConfig {
    ...
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

我错过了什么我做错了什么吗?

【问题讨论】:

  • 您的测试文件存放在哪个文件夹中? src/test 还是 src/androidTest?
  • @RicardoCosteira 我在 src/test 中有它们
  • @RicardoCosteira 这就是问题所在。当我移动我的测试时,一切都开始工作了。这是正确的解决方案。
  • 这么想:P 你正在做仪器测试。对于仪器测试,您需要将文件放在 androidTest 文件夹中。 test 文件夹用于不需要访问 Android 框架的测试。导入依赖项的方式也很重要,因为它们会影响不同的文件夹。您使用androidTestImplementation 导入其中的大部分,因此表示您希望这些依赖项用于 androidTest 文件夹。您拥有的那个 Junit testImplementation 只会影响 src/test 中的测试。

标签: android unit-testing kotlin androidx instrumentation


【解决方案1】:

一个简单的Context 可以解决

androidx.test.core.app.ApplicationProvider.getApplicationContext()

这是核心模块的一部分

androidTestImplementation 'androidx.test:core:1.2.0'

当你使用Robolectric时,你也可以把它当作

testImplementation 'androidx.test:core:1.2.0'

【讨论】:

  • 这就是整个问题。之前提到的core包我已经导入了,ApplicationProvider仍然无法解析。
  • 对。 AndroidTest 和 Test 有不同的依赖关系。如果您使用 Robolectric,请查看答案。如果没有,你应该在没有上下文和内存的情况下构建你的数据库
猜你喜欢
  • 2019-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多