任务:
让连接的Android测试在Android M上运行良好.
题:
如何在运行连接Android测试时启用读/写联系人权限?
问题:
我知道pm命令可以启用apk的权限.
adb shell pm grant <PACKAGE_NAME> <PERMISSION_NAME>
Run Code Online (Sandbox Code Playgroud)
我想运行可以在真正的apis和mock apis上运行的测试.如果我无法在gradle DSL中触发pm命令,则出于安全原因,测试代码无法触及真正的api.
我尝试将该步骤添加为第一项connectedAndroidTest (connectedInstrumentTest)
任务.它不适用于目标apk还没有安装.使用错误代码调用命令行.
android.testVariants.all { variant ->
variant.connectedInstrumentTest.doFirst {
def adb = android.getAdbExe().toString()
exec {
commandLine 'echo', "hello, world testVariants"
}
exec {
commandLine adb, 'shell', 'pm', 'grant', variant.testedVariant.applicationId, 'android.permission.READ_ACCOUNTS'
}
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试添加步骤作为安装任务的最后一步.我开始时没有打电话connectedAndroidTest
.
android.applicationVariants.all { variant ->
if (variant.getBuildType().name == "debug") {
variant.install.doLast {
def adb = android.getAdbExe().toString()
exec {
commandLine 'echo', "hello, world applicationVariants"
}
exec {
commandLine adb, 'shell', 'pm', 'grant', variant.applicationId, 'android.permission.READ_ACCOUNTS'
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的计划是在启动测试之前启用权限.我不知道哪个任务是正确的.虽然他们都打电话,但看起来connectedVariantAndroidTest
并不依赖.installVariant
adb install
我尝试运行pm grant
测试用例.它按预期失败.
我会接受其他解决方案来运行Android测试.
我认为您需要创建自己的任务installDebug
,然后connectedDebugAndroidTest
依赖于您的任务.
人们这样做是为了禁用动画和工作,你强制安装应用程序并在执行android测试之前授予你特定的权限:
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
}
}
Run Code Online (Sandbox Code Playgroud)
您可以将此代码添加到新yourtask.gradle
文件中,并在build.gradle
文件底部添加下一行:
apply from: "yourtask.gradle"
Run Code Online (Sandbox Code Playgroud)
并在适当的清单中声明您的许可
<uses-permission android:name="android.permission.READ_ACCOUNTS" />
Run Code Online (Sandbox Code Playgroud)
更新:
修复了commandLine命令,就像你在多个版本的版本上所做的那样,谢谢.
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()}"
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2563 次 |
最近记录: |