gpt4 book ai didi

android - 运行连接的 Android 测试时如何启用读/写联系人权限?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:27:41 24 4
gpt4 key购买 nike

任务:

让连接的 Android 测试在 Android M 上运行良好。

问题:

如何在运行连接的 Android 测试时启用读/写联系人权限?

问题:

我知道pm命令可以开启apk的权限。

adb shell pm grant <PACKAGE_NAME> <PERMISSION_NAME>

我想运行可以在真实 API 和模拟 API 上运行的测试。如果我无法在 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'
}
}
}

我尝试将该步骤添加为安装任务的最后一步。当我启动 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'
}
}
}
}

我的计划是在启动测试之前启用权限。我不知道哪个任务是合适的。看起来 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
}
}

您可以将此代码添加到新的 yourtask.gradle 文件中,并在 build.gradle 文件的底部添加下一行:

apply from: "yourtask.gradle"

并在适当的 list 中声明您的许可

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

更新:

修复了命令行命令,就像您在 your version for multiple variants 上所做的那样,谢谢。

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()}"
}
}

关于android - 运行连接的 Android 测试时如何启用读/写联系人权限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33759583/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com