Skip to content

自定义 SourceSets (测试隔离)

源:配置 SourceSets

默认情况下,Android 只有 main, test, 和 androidTest。但随着项目复杂度增加,你可能需要一种比单元测试重、比真机 UI 测试轻的“集成测试 (Integration Test)”。

1. 定义新的 SourceSet

android 块中配置:

kotlin
android {
    sourceSets {
        create("intTest") {
            compileClasspath += sourceSets.getByName("main").output
            runtimeClasspath += sourceSets.getByName("main").output
        }
    }
}

此时,你可以在项目目录下新建 src/intTest/kotlin 文件夹。

2. 关联依赖

你需要为新的 SourceSet 单独配置依赖:

kotlin
dependencies {
    "intTestImplementation"(libs.junit)
    "intTestImplementation"(libs.truth)
    // 包含 main 模块的代码
    "intTestImplementation"(project(":app")) 
}

3. 创建运行任务 (Task)

你需要告诉 Gradle 如何运行这些集成测试:

kotlin
val intTestTask = tasks.register<Test>("integrationTest") {
    description = "运行集成测试"
    group = "verification"
    
    testClassesDirs = android.sourceSets.getByName("intTest").output.classesDirs
    classpath = android.sourceSets.getByName("intTest").runtimeClasspath
}

// 挂载到 check 任务中
tasks.named("check") {
    dependsOn(intTestTask)
}

4. 为什么要这么做?

  • 关注点分离: 单元测试跑得快,集成测试跑得慢。通过隔离,你可以快速运行单元测试而不受干扰。
  • 依赖隔离: 集成测试可能需要 MockWebServer 等重型依赖,隔离后不会污染 test 目录。 扫盲:现在你可以在 Android Studio 的 Build Variants 视图中看到 intTest 的切换选项了。