未解决的androidx类,用于编写单元测试

时间:2019-08-27 11:36:40

标签: android unit-testing kotlin androidx instrumentation

我正在尝试编写我的第一个测试,但在找出正确的依赖项以使所有功能正常工作时遇到了问题。这是我的测试课

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"
}

我想念我在做错什么吗?

1 个答案:

答案 0 :(得分:1)

简单的Context可以通过

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

这是核心模块的一部分

androidTestImplementation 'androidx.test:core:1.2.0'

使用 Robolectric 时,也可​​以将其作为

testImplementation 'androidx.test:core:1.2.0'