How to request permissions on Android Marshmallow for JUnit tests

I want to run JUnit tests against my library and I want to ask the user to provide all the necessary permissions before starting the test (because I need, for example, to read some files from the device storage during automatic tests).

I know how to do this by adding a task to gradle and running it from cmd, it works well. But I need to ask the user (or do it automatically) when I conducted the tests using the IDE .

I tried to add a permission request to the MainActivity.onCreate () of the test application, but no luck, because MainActivity does not run for all tests.

Does anyone have any ideas?

Also, do not talk about adding a gradle grant task to the execution configuration. it works, but is unusable, needs something more unified.

0
java android android-6.0-marshmallow android-permissions junit
source share
1 answer

I found a solution to my problem. It was easy:

you need to create a new task in the build.gradle file at the application level as follows:

 android.applicationVariants.all { variant -> def applicationId = variant.applicationId def adb = android.getAdbExe().toString() def variantName = variant.name.capitalize() def grantPermissionTask = tasks.create("create${variantName}Permissions") << { println "Granting permissions" "${adb} shell pm grant ${applicationId} android.permission.ACCESS_FINE_LOCATION".execute() "${adb} shell pm grant ${applicationId} android.permission.WRITE_EXTERNAL_STORAGE".execute() "${adb} shell pm grant ${applicationId} android.permission.READ_EXTERNAL_STORAGE".execute() } } 

then add the following dependency:

 preBuild.dependsOn "createDebugPermissions" 

after that, all necessary permissions will be granted when starting any test

+2
source share

All Articles