1

I am writting an UI test in Espresso for an Android app. I need to take an screenshot of the screen to verify the UI, I do it through the UiDevice.takeScreenshot() method.

This method is throwing an Exception because the app has no write permissions, in order to run this UI tests, I need to specifically add the android permission in the AndroidManifest:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Then execute the app, go to Android settings, enable this permission; and then I can run the UI test. After that I need to go back to AndroidManifest, remove this permission (because I only need it for the UI tests).

Is there any cleaner way to achieve this without having to touch AndroidManifest and automatically grant write external storage permission for the UI tests only?

svprdga
  • 2,171
  • 1
  • 28
  • 51

1 Answers1

1

You can put the <uses-permission> element in an AndroidManifest.xml file in your androidTest/ source set, so it does not affect your production code.

To automatically grant the runtime permission during tests, you can try the new GrantPermissionRule. Or, use other techniques to grant the permission as part of your test suite. In the end, they all use:

adb shell pm grant com.package.myapp android.permission.<PERMISSION>
adb shell pm revoke com.package.myapp android.permission.<PERMISSION>

...either from Gradle or from your test code.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491