Android Studio -- 清除 Instrumentation 测试的应用程序数据

Android Studio -- clear application data for Instrumentation Test

如何让 Android Studio (AndroidJunitRunner) 在不手动 运行ning adb 命令的情况下清除仪器测试之前的应用程序数据?

我发现 android.support.test.runner.AndroidJUnitRunner 有点作弊——它实际上从未调用 connectedCheckconnectedAndroidTest

  1. 当从命令行 运行 时 $ gradle connectedCheck

    :MyMainApp:assembleDebug UP-TO-DATE
    :MyMainApp:assembleDebugTest UP-TO-DATE
    :MyMainApp:clearMainAppData
    :MyMainApp:connectedCheck
    
  2. 当 运行 从 IDE 中单击仪器测试配置时(绿色 Android 机器人徽标带有 red/green 箭头)

    **Executing tasks: [:MyMainAppApp:assembleDebug, :MyMainAppApp:assembleDebugTest]**
    

    如你所见,最后一个gradle目标是assembleDebugTest

我在 build.gradle 中的 connectedCheck 上添加了一个挂钩,以便在开始仪器测试之前清除主应用程序的数据。

// Run 'adb' shell command to clear application data of main app for 'debug' variant
task clearMainAppData(type: Exec) {
    // we have to iterate to find the 'debug' variant to obtain a variant reference
    android.applicationVariants.all { variant ->
        if (variant.name.equals("debug")) {
            def clearDataCommand = ['adb', 'shell', 'pm', 'clear', getPackageName(variant)]
            println "Clearing application data of ${variant.name} variant: [${clearDataCommand}]"
            commandLine clearDataCommand
        }
    }
}
// Clear Application Data (once) before running instrumentation test
tasks.whenTaskAdded { task ->
    // Both of these targets are equivalent today, although in future connectedCheck
    // will also include connectedUiAutomatorTest (not implemented yet)
    if(task.name.equals("connectedAndroidTest") || task.name.equals("connectedCheck" )){
        task.dependsOn(clearMainAppData)
    }
}

我意识到我也可以在主应用程序中实现一个 'clear data' 按钮并让检测应用程序通过 UI 单击,但我发现该解决方案不受欢迎。

我查看了 AndroidJUnitRunner API 并且有通过 Runlistener 接口的挂钩,但是挂钩是在测试应用程序的上下文中,即 运行ning 在设备上, Android 禁止一个应用程序修改另一个应用程序。 http://junit.sourceforge.net/javadoc/org/junit/runner/notification/RunListener.html

最好的答案 如果你能帮我从 Android Studio 中自动触发以下之一:

如果有其他方法,我也洗耳恭听。当然,对于设备测试自动化,应该有一种清晰的方法来清除应用程序数据?

谢谢!

我知道这已经有一段时间了,希望到现在你已经解决了这个问题。

我今天 运行 遇到了同样的问题,并在没有任何解决方案的情况下崩溃了。

但我设法通过从测试配置调用我的任务使其工作。

第 1 步:转到您的测试配置

第 2 步:只需添加您创建的 gradle 任务

顺便说一句,我的任务看起来像这样:

task clearData(type: Exec) {
  def clearDataCommand = ['adb', 'shell', 'pm', 'clear', 'com.your.application']
  commandLine clearDataCommand
}

希望这会对某人有所帮助:)

使用 Android Test Orchestrator 可以更轻松地通过 gradle 脚本提供此选项。

android {
  defaultConfig {
   ...
   testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

   // The following argument makes the Android Test Orchestrator run its
   // "pm clear" command after each test invocation. This command ensures
   // that the app's state is completely cleared between tests.
   testInstrumentationRunnerArguments clearPackageData: 'true'
 }

下面是 Android Test Orchestrator

的 link

https://developer.android.com/training/testing/junit-runner#using-android-test-orchestrator