Skip to content Skip to sidebar Skip to footer

How To Enable Read/write Contacts Permission When Run Connected Android Test?

Task: Let connected Android tests work well on Android M. Question: How to enable read/write contacts permission when run connected Android test? Problem: I know pm command could e

Solution 1:

I think that you need to create your own task depending on installDebug and then make connectedDebugAndroidTest depend on your task.

People does it to disable animations and works, you force the app installation and grant your specific permission before the android tests are executed like this:

def adb = android.getAdbExe().toString()

task nameofyourtask(type: Exec, dependsOn: 'installDebug') { //or install{productFlavour}{buildType}
    group = 'nameofyourtaskgroup'
    description = 'Describe your task here.'
    def mypermission = 'android.permission.READ_ACCOUNTS'
    commandLine "$adb shell pm grant ${variant.applicationId} $mypermission".split(' ')
}

tasks.whenTaskAdded { task ->
    if (task.name.startsWith('connectedDebugAndroidTest')) { //or connected{productFlavour}{buildType}AndroidTest
        task.dependsOn nameofyourtask
    }
}

You can add this code to a new yourtask.gradle file and add the next line at the bottom of the build.gradle file:

apply from: "yourtask.gradle"

And declare your permission in the proper manifest

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

Update:

Fixed commandLine command like you did on your version for multiple variants, thanks.

android.applicationVariants.all { variant ->
    if (variant.getBuildType().name == "debug") {
        task "configDevice${variant.name.capitalize()}" (type: Exec){
            dependsOn variant.install

            group = 'nameofyourtaskgroup'
            description = 'Describe your task here.'

            def adb = android.getAdbExe().toString()
            def mypermission = 'android.permission.READ_ACCOUNTS'
            commandLine "$adb shell pm grant ${variant.applicationId}$mypermission".split(' ')
        }
        variant.testVariant.connectedInstrumentTest.dependsOn "configDevice${variant.name.capitalize()}"
    }
}

Post a Comment for "How To Enable Read/write Contacts Permission When Run Connected Android Test?"