使用 TestKit 时,如何开启 --configuration-cache 进行集成测试?

解读

在国内 Android 与微服务项目面试中,**“配置缓存”**是 Gradle 性能调优的高频考点。面试官通过 TestKit 场景考察两点:

  1. 你是否理解 --configuration-cache 的本质(把配置阶段序列化到磁盘,第二次构建跳过配置)。
  2. 你是否能在 GradleRunner 这一官方集成测试框架里正确、稳定地打开该标志,并处理 Task 序列化兼容性问题。
    很多候选人只回答“在 args 里加字符串”,却忽略 TestKit 自身守护进程隔离、Groovy 闭包序列化失败、buildSrc 与 included build 限制等国内工程常见坑,导致面试被追问“为什么本地通过、CI 随机失败”。

知识点

  1. GradleRunner API:withArguments、withJvmArguments、withTestKitDir、withDebug 等。
  2. --configuration-cache 与 --configuration-cache-problems=warn/fail 组合使用,可提前暴露序列化缺陷。
  3. TestKit 默认启用自己的守护进程,与命令行不同,需显式传递参数。
  4. Task 实现类必须实现 Serializable,否则会在缓存写入阶段抛 NotSerializableException。
  5. **国内常见 CI 镜像(阿里云、腾讯云)**默认 JDK 8u302 以下存在 SerializedLambda 缺陷,需升级 JDK 11+ 或加 -Dorg.gradle.java.home。
  6. buildSrc 与 included build 在 7.4 之前无法被缓存,面试时需说明版本差异。
  7. withTestKitDir 指向可写路径,避免 Docker 容器只读层导致缓存写入失败。

答案

在 TestKit 中开启 --configuration-cache 的最小可运行模板如下(Kotlin DSL 写法,Groovy 同理):

@Test
fun `configuration cache works`() {
    val result = GradleRunner.create()
        .withProjectDir(File("src/test/fixtures/sample-app"))
        .withPluginClasspath()          // 引入被测插件
        .withArguments(
            "build",
            "--configuration-cache",
            "--configuration-cache-problems=fail", // 国内 CI 强制失败,提前暴露问题
            "--build-cache",                       // 与远程缓存叠加,面试加分
            "--info"
        )
        .withTestKitDir(File("build/test-kit"))   // 确保目录可写,避免容器只读层
        .withJvmArguments("-Xmx1g")               // 国内云主机内存小,显式限制
        .forwardOutput()                          // 本地调试可看到序列化异常栈
        .build()

    // 断言配置缓存被重用
    assertTrue(result.output.contains("Configuration cache is an incubating feature"))
    assertTrue(result.output.contains("Reusing configuration cache"))
}

关键点:

  1. withArguments 里必须显式加入 --configuration-cache,TestKit 不会读取 ~/.gradle/gradle.properties。
  2. --configuration-cache-problems=fail 让测试在序列化错误时直接失败,防止国内 CI 随机挂。
  3. withTestKitDir 指向 build 目录,保证并发任务之间隔离,又能在 CI 缓存层整体复用。
  4. 如果被测插件在 buildSrc 中,需升级到 Gradle 7.5+ 并在 settings.gradle.kts 里启用
    enableFeaturePreview("STABLE_CONFIGURATION_CACHE"),否则面试会被追问“为什么本地成功、线上失败”。

拓展思考

  1. 并行集成测试稳定性:国内大厂多模块项目常把 TestKit 测试放到 GitHub Action 的 matrix 里,需配合
    .withArguments("--parallel", "--max-workers=2") 与 org.gradle.workers.max 系统属性,避免容器 vCPU 数抖动导致死锁。
  2. 缓存命中率调优:在阿里云 OSS 搭建远程构建缓存后,可在 TestKit 里加
    -Dorg.gradle.unsafe.configuration-cache-problems=warn 做灰度,逐步修复序列化问题,再提升为 fail。
  3. 版本矩阵:Android Gradle Plugin 7.3 才兼容配置缓存,面试时需说明 AGP 与 Gradle 版本匹配表,否则会被追问“为什么开启后 DexArchiveBuilderTask 报错”。
  4. 故障演练:故意在 Task 里写 project.objects.property(String::class.java) 未标记 @Internal 的属性,观察 TestKit 测试失败,再修复并展示 @Internal、@ReplacedBy、@PathSensitive 等注解用法,可体现深度调优能力。