【发布时间】: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 文件夹。您拥有的那个 JunittestImplementation只会影响 src/test 中的测试。
标签: android unit-testing kotlin androidx instrumentation