android - 如何使现代 Multidex 与旧 API 上的仪器测试配合使用

标签 android android-multidex android-instrumentation

我有一个使用 Multidex 设置的应用程序,似乎可以加载并在较旧的 Android API 上工作,但是,我有时会从仪表测试运行程序中收到错误,无法找到任何测试。我可以找到有关如何将 multidex 添加到 Android 应用程序的详细信息,但有多种解决方案取决于所使用的支持库,并且似乎没有一个解决方案可以直接解决使用当前推荐的 AndroidX 库使用 multidex 运行测试的问题。在 Android API 级别 19 上,我当前收到此错误:

$ ./gradlew connectedCheck
> Task :app:connectedDebugAndroidTest
Starting 0 tests on API-19(AVD) - 4.4.2

com.android.build.gradle.internal.testing.ConnectedDevice > No tests found.[API-19(AVD) - 4.4.2] FAILED 
No tests found. This usually means that your test classes are not in the form that your test runner
expects (e.g. don't inherit from TestCase or lack @Test annotations).

在 API 级别 21 的模拟器上运行此程序可成功运行所有测试。我没有启用 Proguard 或 minify。为了启用 Multidex,我进行了以下更改。我将其添加到应用程序的 build.gradle 中:

android {
    defaultConfig {
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
}

dependencies {
    implementation "androidx.multidex:multidex:2.0.1"
    androidTestImplementation 'org.mockito:mockito-core:3.4.6'
    androidTestImplementation 'com.linkedin.dexmaker:dexmaker:2.28.0'
    androidTestImplementation 'com.linkedin.dexmaker:dexmaker-mockito:2.28.0'
}

我的 list 定义了一个继承自 android:name 属性中的 androidx.multidex.MultiDexApplication 的类。

我看到有人提到将 multidex 测试运行程序添加到测试应用程序的 AndroidManifest.xml 中,但我目前没有明确的 list ,而且它似乎只存在于旧 Android 支持库的上下文中,不是 AndroidX。我需要做什么才能让仪器测试在 API 级别 16-19 上与 Multidex 和 AndroidX 配合使用?

最佳答案

My manifest defines a class that inherits from androidx.multidex.MultiDexApplication

  1. 这仅在您不重写代码中的 Application 类时才有效。否则,您的 Application 类应扩展 MultiDexApplication,如 documentation 中所述。

  2. 现在可以找到测试,但会崩溃,我通过将测试运行器类添加到 build.gradle 中,将测试运行器类保留在第一个 dex 中,解决了这个问题:

android {
  ...
  buildTypes {
    ...
    debug {
      multiDexKeepProguard file('multidex-config.pro')
    }
  }
}

multidex-config.pro包含:

-keep class androidx.test.** { *; }

关于android - 如何使现代 Multidex 与旧 API 上的仪器测试配合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64084533/

相关文章:

android - 我怎样才能重新创建 fragment ?

android - InstrumentationRegistry.getContext() 替换示例

android - 在 Android 测试中创建和使用 gradle 或系统属性

android - 在正常和测试编译中添加的 Espresso 依赖项

安卓 : Add your own application to accounts

android - Firestore 获取 DocumentSnapshot 字段的值

java - Android 强制关闭 应该已经设置了字幕 Controller

android - 重复的 Zip 条目 MultiDex.class

android - 错误 ':app:packageAllDebugClassesForMultiDex'。 > java.util.zip.ZipException : duplicate entry:

android - Twitter Fabric +MultiDex 导致 NoClassDefFoundError