android - “不能将测试根与非测试根混合”
问题描述
我正在尝试为 Android 应用程序运行检测测试,但出现此编译时错误:
Cannot mix test roots with non-test roots:
Non-Test Roots: com.my.application.MyApplication
Test Roots: [com.my.test.ActivityTest]
该应用程序使用带有注释的自定义应用程序@HiltAndroidApp
,因为文档暗示这是 Hilt 所必需的。
我的测试遵循这种模式:
@RunWith(AndroidJUnit4.class)
@HiltAndroidTest
class MyTest {
@Rule
public HiltAndroidRule hiltRule = new HiltAndroidRule(this);
@Inject
SomeStuff stuff;
@Before
public void setUp() {
hiltRule.inject();
}
应用程序运行器正在创建一个普通的 Hilt 应用程序:
public class MyAppRunner extends AndroidJUnitRunner {
@Override
public Application newApplication(ClassLoader cl, String className, Context context)
throws InstantiationException, IllegalAccessException, ClassNotFoundException {
return super.newApplication(
cl, HiltTestApplication.class.getName(), context);
运行测试时,我得到上面概述的编译时错误。我想引用MyApplication
来自应用程序的AndroidManifest.xml
文件。
我尝试使用@CustomTestApplication
with MyApplication
,但自定义测试应用程序显然不适用于带有@HiltAndroidApp
.
使用基于 Hilt 的应用程序设置测试的正确方法是什么?
解决方案
要在插桩测试中使用 Hilt 测试应用程序,您需要配置一个新的测试运行程序。这使得 Hilt 适用于您项目中的所有插桩测试。执行以下步骤:
在 androidTest 文件夹中创建一个扩展 AndroidJUnitRunner 的自定义类。
覆盖 newApplication 函数并传入生成的 Hilt 测试应用程序的名称。
类 CustomTest : AndroidJUnitRunner() {
override fun newApplication(cl: ClassLoader?, name: String?, context: Context?): Application { return super.newApplication(cl, HiltTestApplication::class.java.name, context) }
}
接下来,按照检测单元测试指南中的说明在 Gradle 文件中配置此测试运行程序。确保使用完整的类路径:
android {
defaultConfig {
// Replace com.example.android.dagger with your class path.
testInstrumentationRunner "com.example.android.dagger.CustomTestRunner"
}
}
来源:https ://developer.android.com/training/dependency-injection/hilt-testing
推荐阅读
- python - 为什么我的 NLP 函数仍会产生本应被停用词阻止的元素?
- flask - 在我设置导致数据丢失的值后,flask-session 会话 id 发生变化
- javascript - 正则表达式导致 console.log 为空
- reactjs - 将 JWT 临时存储在反应本机变量中是否安全?
- python - Android Play 计费库:skuDetailsList 的大小为 0
- haskell - 如何防止堆栈(haskell)运行hpack?
- html - 边框半径不适用于更宽的屏幕
- sql - 如何展平嵌套的字符串?
- python-3.x - 单击python tkinter时如何使按钮重复使用它的命令
- python - Discord py - AttributeError:“str”对象没有属性“remove_roles”