是否可以在没有活动但使用 AppCompat 依赖项的 Android 模块中运行仪器测试?我正在尝试运行一个简单的测试,但只有在移动到应用程序模块时才有效。
使用类进行测试
/**
* Typical email validation
* */
fun validateEmail(email: String?): ValidationResult {
val emailInput: String? = email?.trim()
return when {
(emailInput.isNullOrBlank()) -> {
ValidationResult(
isSuccessful = false,
errorMessageResource = R.string.field_required
)
}
(Patterns.EMAIL_ADDRESS.matcher(emailInput).matches().not()) -> {
ValidationResult(
isSuccessful = false,
errorMessageResource = R.string.invalid_email
)
}
else -> {
ValidationResult(
isSuccessful = true
)
}
}
}
测试脚本
@RunWith(AndroidJUnit4::class)
class ValidationUtilsTest {
@Test
fun invalidEmails_returnsFalse() {
val invalidEmailList = listOf(
"plainaddress",
"#@%^%#$@#$@#.com",
"@example.com",
"Joe Smith <[email protected]>",
"email.example.com",
"email@[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"あいうえお@example.com",
"[email protected] (Joe Smith)",
"email@example",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
)
val listResult = mutableListOf<Boolean>()
for (invalidEmail in invalidEmailList) {
val result = ValidationUtils.validateEmail(invalidEmail)
listResult.add(result.isSuccessful)
}
assertThat(listResult.any { true }).isFalse()
}
}
出现这些错误:
java.lang.RuntimeException: Unable to instantiate instrumentation ComponentInfo
Caused by: java.lang.ClassNotFoundException: Didn't find class "androidx.test.runner.AndroidJUnitRunner" on path: DexPathList
结构
- app
- libs
- androidTest
- test
终于找到问题了,需要添加runner依赖
androidx.test:runner
。