4

We're trying to write instrumentationTest for our app.

For example I want to write test for authorization/registration.

However before every test I want to be unauthorized? so I need to clean all data, delete db, etc.

So is there any way to delete app or app's data before every test?

tomrozb
  • 25,773
  • 31
  • 101
  • 122
Korniltsev Anatoly
  • 3,676
  • 2
  • 26
  • 37

3 Answers3

13

Using Android studio, you can create a test configuration that first uninstalls your app before running a test.

Create a new External Tool.

  1. Go to Preferences -> External Tools.
  2. Click on the "+" icon to create a new tool.
  3. Set Name to "Uninstall myApp" (or whatever you like)
  4. Set Group to "Custom Tools" (or whatever you like)
  5. Set Program to "adb"
  6. Set Parameters to:
    uninstall name.of.your.package
    
  7. Click OK.

You can test that this new tool works by clicking Tools -> External Tools -> "Uninstall myApp" (Or for older Android Studio versions, Tools->Custom Tools->"Uninstall myApp").

Step 2. Create or edit your test configuration.

  1. Go to Edit Configurations.
  2. Choose the Android Tests configuration that you'd like to modify.
  3. Under "Before launch: ...", click the "+" icon.
  4. Choose "Run External Tool".
  5. In the popup, choose your new tool "Uninstall myApp".
  6. Use the arrows so that the External Tool is above any other commands like Gradle-aware Make".
  7. Click Ok.

Now, when you run this configuration, your app should be uninstalled first, before your tests are run.

Sharing

Newer Android Studio version's have "Store as project file" option (in their "Edit Configurations..." dialog).

But that only saves tool's build-step (second step of above), and to to share "External Tools" itself through repository, see: Share or Export External tools without using jar-file

Top-Master
  • 7,611
  • 5
  • 39
  • 71
dannyhan12
  • 942
  • 8
  • 9
3

This question was asked in '13. We have come a long way since then. Android has jUnit test runner that comes with a cleanup mechanism under test orchestrator.

Check it out here https://developer.android.com/training/testing/junit-runner

Jasmeet Singh
  • 325
  • 2
  • 10
2

Use Annotations eg:

@BeforeEach

and put your clean up code there.

Jigish Chawda
  • 2,148
  • 1
  • 22
  • 29
  • Topic starter (and I too!) is interesting how to remove an apk after or before the test. How would you do this under this annotation? We have ```$adb uninstall ```, but I do not see a way how to do it from ```androidTest```. It can be done as part of gradle tasks which first prepare the environment and later execute test suite, but I am looking for a simpler option. – Gleichmut Jun 14 '23 at 16:19
  • 1
    As pointed out by Jasmeet, ```Android Test Orchestrator``` might be a right option to do this https://developer.android.com/training/testing/instrumented-tests/androidx-test-libraries/runner#architecture – Gleichmut Jun 14 '23 at 16:24