Android revoke permission at start of each test

后端 未结 6 849
花落未央
花落未央 2021-01-17 11:49

I\'m using Espresso and UIAutomator to write my test cases. I\'m testing external storage permissions when it\'s denied and when it\'s allowed. I have different test cases w

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-17 11:58

    ADB has the capability to revoke permissions, but it can't be called from an instrumentation test because revoking a permission will restart the entire app process and end the test with failure. The following Kotlin code will perform the revocation, but will crash your test if a permission gets revoked.

    /**
     *  Will revoke, but also CRASH if called by a test
     *  Revocation requires a full process restart, which crashes your test process.
     */
    fun revokePermissions(vararg permissions: String) {
        permissions.forEach {
            InstrumentationRegistry.getInstrumentation().uiAutomation.
                    executeShellCommand("pm revoke ${getTargetContext().packageName} $it")
        }
    }
    

    If you run your tests from a shell script, you can simply use ONE of the following shell commands before starting each test.

    adb shell pm revoke com.package.appname android.permission.CAMERA
    adb shell pm reset-permissions com.package.appname
    adb shell pm clear com.package.appname
    

    The same crash happens whether you revoke permissions from a custom AndroidJUnitRunner's onCreate() or onStart() or from the middle of a test. You cannot revoke permissions during an instrumentation test without crashing even when the activity is not opened yet.

    It seems like the best option is to revoke all permissions from Gradle before running any instrumentation test and then you can re-enable any permissions you want set before the test starts using a GrantPermissionRule.

    The Android Test Orchestrator was planned to clear all data automatically between each test, but that feature is still not there today. I filed a bug you can vote up to have automatic cleanup between tests.

提交回复
热议问题