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

Android Instrumentation Orchestrator的clearPackageData不清除数据问题

Android Instrumented测试Orchestrator数据未清除问题排查

我已在build.gradle中配置以下内容,以启用Orchestrator并清除测试间数据:

defaultConfig {
 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
 testInstrumentationRunnerArguments clearPackageData: 'true'
}

testOptions {
  animationsDisabled = true
  execution 'ANDROIDX_TEST_ORCHESTRATOR'
}

dependencies {
 androidTestImplementation 'androidx.test:runner:1.5.1'
 androidTestUtil 'androidx.test:orchestrator:1.4.2'
}

但启动测试时,数据仍会在测试运行间保留,无论从Android Studio还是通过Gradle命令./gradlew connectedStageDebugAndroidTest执行都是如此。请问哪里配置出错了?


可能的问题及修复方案

  1. 修正clearPackageData参数类型
    testInstrumentationRunnerArguments中的clearPackageData接受布尔值而非字符串,将'true'改为不带引号的true:
testInstrumentationRunnerArguments clearPackageData: true

字符串形式的'true'可能不会被测试运行器正确解析为布尔值,导致清除逻辑未触发。

  1. 确保Orchestrator实际生效
    检查测试日志,确认是否存在Test orchestrator is running的日志条目。如果没有,说明Orchestrator未被正确启用:
  • 确认testOptions.execution的取值是'ANDROIDX_TEST_ORCHESTRATOR'(注意大小写,必须全大写)
  • 检查build变体的配置:如果stageDebug是自定义productFlavor,确认该flavor没有覆盖testOptions或testInstrumentationRunner配置
  1. 版本兼容性问题
    androidx.test:runner和androidx.test:orchestrator版本需保持一致,你当前使用runner 1.5.1搭配orchestrator 1.4.2,版本不匹配可能导致功能异常。将orchestrator升级到1.5.1:
androidTestUtil 'androidx.test:orchestrator:1.5.1'
  1. 测试类内方法间数据保留的特殊情况
    Orchestrator的clearPackageData是在每个测试类启动前清除应用数据,同一测试类内的多个测试方法会共享同一个应用进程,因此类内方法间的数据不会被自动清除。如果需要类内方法间也清除数据,需在@Before方法中手动清理数据(比如删除数据库、SharedPreferences等),或使用@TestInstance(Lifecycle.PER_METHOD)确保每个测试方法使用独立的测试实例(但进程仍共享,需结合手动清理)。

  2. Gradle命令行执行的额外检查
    执行./gradlew connectedStageDebugAndroidTest --info查看详细日志,搜索clearPackageData或orchestrator相关条目,确认参数是否被正确传递给测试运行器。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 02:05:24