【问题标题】:"Cannot mix test roots with non-test roots"“不能将测试根与非测试根混合”
【发布时间】:2020-12-09 07:38:16
【问题描述】:

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

我尝试将@CustomTestApplicationMyApplication 一起使用,但自定义测试应用程序显然不适用于带有@HiltAndroidApp 注释的应用程序。

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

【问题讨论】:

    标签: android dagger-hilt


    【解决方案1】:

    要在插桩测试中使用 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

    【讨论】:

    • 谢谢,但这正是我在问题中已经写的内容?我已经设置了这个测试运行器,并且我已经确认它正在运行。
    猜你喜欢
    • 2019-01-30
    • 1970-01-01
    • 2010-09-12
    • 2017-02-08
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    • 2017-01-17
    相关资源
    最近更新 更多