用于编写单元测试的未解析androidx类
我正在尝试编写我的第一个测试,但我很难找出正确的依赖项来让所有的东西都正常工作。这是我的测试课用于编写单元测试的未解析androidx类,android,unit-testing,kotlin,androidx,instrumentation,Android,Unit Testing,Kotlin,Androidx,Instrumentation,我正在尝试编写我的第一个测试,但我很难找出正确的依赖项来让所有的东西都正常工作。这是我的测试课 class EmployeeDatabaseTest { private lateinit var employeeDao: EmployeeDAO @Before fun setup() { EmployeeDatabase.TEST_MODE = true employeeDao = EmployeeDatabase.getDatabase
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"
}
我错过了什么吗?我做错了什么吗?一个简单的
上下文可以用
androidx.test.core.app.ApplicationProvider.getApplicationContext()
这是核心模块的一部分
androidTestImplementation 'androidx.test:core:1.2.0'
当您使用Robolectric时,您也可以将其作为
testImplementation 'androidx.test:core:1.2.0'
您的测试文件在哪个文件夹中?src/test还是src/androidTest?@RicardoCosteira我在src中有它们/test@RicardoCosteira这就是问题所在。当我移动测试时,一切都开始工作了。这是正确的解决方案。这样想:P你在做仪器测试。对于插装测试,您需要将文件放在androidTest文件夹中。测试文件夹用于不需要访问Android框架的测试。导入依赖项的方式也很重要,因为它们会影响不同的文件夹。您正在使用androidTestImplementation
导入它们中的大多数,因此表示您希望androidTest文件夹具有这些依赖项。您拥有的JunittestImplementation
只会影响src/test中的测试。这就是整个问题所在。我已经导入了前面提到的核心包,ApplicationProvider仍然无法解析。对。AndroidTest和Test具有不同的依赖关系。如果你使用机器人,看看答案。如果不是,您应该在没有上下文和内存的情况下构建数据库