如何为JUnit测试在Android Marshmallow上请求权限 [英] How to request permissions on Android Marshmallow for JUnit tests
问题描述
我想对我的库执行JUnit测试,并想要求用户在测试开始之前授予所有必需的权限(例如,因为在自动化测试期间,我需要从设备存储中读取一些文件).
I want to execute JUnit tests against my lib and want to ask user to grant all required permissions before the test starts (because I need to read some files from device storage during the automated tests for example).
我知道如何通过添加任务到gradle并从cmd运行它来实现它,它运行良好.但是我需要使用IDE 运行测试时询问用户(或自动执行).
I know how to make it by adding a task to gradle and run it from cmd, it is working well. But I need to ask user (or do it automatically) when I ran my tests using IDE.
我尝试向测试应用程序的MainActivity.onCreate()添加权限请求,但没有运气,因为MainActivity并非针对所有测试都启动.
I've tried to add permission request to MainActivity.onCreate() of test app but no luck because MainActivity starts not for all tests.
有人有什么想法吗?
此外,请不要谈论将gradle授予任务添加到执行配置中.它正在工作,但无法使用,需要更统一的内容.
Also, please do not talk about adding gradle grant task to execution configuration. it is working but unusable, needs something more unified.
推荐答案
我找到了解决问题的方法.很简单:
I found a solution to my problem. It was easy:
需要像这样在应用程序级build.gradle
文件中创建新任务:
needs to create a new task in app-level build.gradle
file like this:
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()
}
}
然后添加以下依赖项:
preBuild.dependsOn "createDebugPermissions"
之后,当您运行任何测试时,所有必需的权限都将被授予
after that, all required permissions will be granted when you run any test
这篇关于如何为JUnit测试在Android Marshmallow上请求权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!