Android Studio — clear application data for Instrumentation Test

I know it’s been a while, and hopefully by now you will have this issue sorted.

I ran into that same issue today, and crashed here without any solution.

But I managed to make it work by calling my task from the test configuration.

Step 1 : Go to your test configuration

Your test configuration

Step 2 : Simply add the gradle task you created

Simply call your gradle task from here

By the way, the task in my case simply looks like this :

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

Hope this will help someone 🙂

With Android Test Orchestrator it is easier to provide this option via gradle script.

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'

Below is the link for Android Test Orchestrator

Leave a Comment