我正在尝试编写我的第一个测试,但在找出正确的依赖项以使所有功能正常工作时遇到了问题。这是我的测试课
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"
}
我想念我在做错什么吗?
答案 0 :(得分:1)
简单的Context
可以通过
androidx.test.core.app.ApplicationProvider.getApplicationContext()
这是核心模块的一部分
androidTestImplementation 'androidx.test:core:1.2.0'
使用 Robolectric 时,也可以将其作为
testImplementation 'androidx.test:core:1.2.0'