Sometimes your app features need special permissions to work, like accessing storage or the microphone. When you run automated integration tests on Android, these permissions might not be granted by default.
Why Grant Permissions in Tests?
To fully test features that depend on permissions, your test environment needs to mimic a real user granting those permissions. Manually granting them each time is slow.
Using adb for Permissions
The Android Debug Bridge (adb) tool lets you control Android devices and emulators from your computer. It has a command (pm
) that can manage package permissions.
The Commands
You can grant a permission using adb shell pm grant <package_name> <permission>
. To remove it later, you use adb shell pm revoke <package_name> <permission>
. These commands are run from your computer's terminal, but we can run them from Dart.
Implementing in Flutter with Dart
You can run these adb commands directly from your Flutter integration test code using the Process.runSync
function from Dart's dart:io
library.
Using Process.runSync
This function runs a command line process and waits for it to finish. You give it the command ('adb'
) and a list of arguments (['shell', 'pm', 'grant', ...]
).
The Code Explained
The example code shows a typical setup:
Permissions List
It starts with a list of String
containing the permissions you need, like 'android.permission.WRITE_EXTERNAL_STORAGE'
. Add all the permissions your test requires here.
Package Name
You also need your app's package name, like 'com.apparence.example'
. Make sure this matches your app's package ID.
Granting
Before your actual tests run (e.g., before await integrationDriver();
), you loop through the permissions list and run the grant
command for each one using Process.runSync
. This sets up the environment for the test.
Running Test
Your main test logic runs here (await integrationDriver();
represents this). This is where your test interacts with the app, now that permissions are granted.
Revoking
After the test finishes, you loop through the permissions again and run the revoke
command to clean up the test environment. This is good practice to ensure tests are independent.