首页 > 解决方案 > “不能将测试根与非测试根混合”

问题描述

我正在尝试为 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文件。

我尝试使用@CustomTestApplicationwith MyApplication,但自定义测试应用程序显然不适用于带有@HiltAndroidApp.

使用基于 Hilt 的应用程序设置测试的正确方法是什么?

标签: androiddagger-hilt

解决方案


要在插桩测试中使用 Hilt 测试应用程序,您需要配置一个新的测试运行程序。这使得 Hilt 适用于您项目中的所有插桩测试。执行以下步骤:

  1. 在 androidTest 文件夹中创建一个扩展 AndroidJUnitRunner 的自定义类。

  2. 覆盖 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


推荐阅读