You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何跨Android模块共享CoroutineExecutorExtension等测试扩展类

解决方案

针对Android多模块共享测试工具类的需求,可根据你的AGP版本选择以下两种适配方案:

方案1:修复现有testFixtures配置(适用于AGP 7.0+)

Android Gradle Plugin 7.0及以上版本原生支持Android Library模块的testFixtures功能,你遇到无法访问的问题是配置缺失导致,按以下步骤调整即可:

  1. 调整unittest模块的build.gradle配置:
plugins {
    id 'com.android.library'
    id 'kotlin-android'
    id 'java-test-fixtures'
}
android {
    // 与其他业务模块保持一致的compileSdk、minSdk配置
    compileSdk 33
    defaultConfig {
        minSdk 21
    }
    // 显式开启testFixtures支持
    testFixtures {
        enable = true
    }
    // 按需关闭不需要的构建特性
    buildFeatures {
        buildConfig = false
        aidl = false
        renderScript = false
        shaders = false
    }
}
dependencies {
    // 测试工具类需要的依赖必须添加到testFixtures作用域
    testFixturesImplementation "androidx.arch.core:core-testing:2.2.0"
    testFixturesImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4"
    testFixturesImplementation "org.junit.jupiter:junit-jupiter-api:5.9.2"
    // 其他需要的androidx、kotlin依赖按同样方式添加
}
  1. 修正源集路径:
    如果你的两个扩展类是Kotlin代码,需要放到src/testFixtures/kotlin/com/name/terminal/unittest路径下,Java代码才放到对应java路径下,路径不匹配会导致类无法被识别。
  2. 其他模块的依赖配置保持不变:
testImplementation(testFixtures(project(":unittest")))

同步Gradle后即可正常导入使用。

方案2:独立测试公共模块(适配所有AGP版本)

如果你的AGP版本低于7.0,不想用testFixtures功能,可以采用独立模块的方案,不会将测试代码打入正式包:

  1. 新建名为test-common的Android Library模块
  2. 将两个扩展类直接放到该模块的src/main/kotlin/对应包路径下
  3. 在该模块的build.gradle中添加所有需要的依赖:
plugins {
    id 'com.android.library'
    id 'kotlin-android'
}
android {
    // 与其他业务模块保持一致的compileSdk、minSdk配置
    compileSdk 33
    defaultConfig {
        minSdk 21
    }
}
dependencies {
    implementation "androidx.arch.core:core-testing:2.2.0"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4"
    implementation "org.junit.jupiter:junit-jupiter-api:5.9.2"
    // 其他需要的依赖正常添加即可
}
  1. 在需要使用的模块中添加依赖:
testImplementation(project(":test-common"))

该方案的优势是兼容性强,且由于仅在test作用域引入该模块,完全不会影响正式包的体积和编译逻辑,也不会出现依赖冲突问题。

内容的提问来源于stack exchange,提问作者1048576

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 05:54:04