You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

启用Orchestrator的Espresso测试读取外部存储配置方案咨询

问题:测试APK读取外部配置文件的权限与存储目录问题

我正在构建测试APK,希望从外部文件读取配置值,而非将配置编译进APK。在Espresso的TestRule中编写相关逻辑时,遇到了外部存储权限变更的阻碍:

  • SDK 28/29出现权限错误
  • SDK 30抛出安全异常:Permission android.permission.MANAGE_EXTERNAL_STORAGE requested by $myPackageNameHere is not a changeable permission type

尝试的权限申请与文件读取代码

val instrumentation = InstrumentationRegistry.getInstrumentation()
val packageName =  instrumentation.context.packageName
with(instrumentation.uiAutomation) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        grantRuntimePermission(packageName, Manifest.permission.MANAGE_EXTERNAL_STORAGE)
    }
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
        grantRuntimePermission(packageName, Manifest.permission.READ_EXTERNAL_STORAGE)
        grantRuntimePermission(packageName, Manifest.permission.WRITE_EXTERNAL_STORAGE)
    }
}

val dir = Environment.getExternalStorageDirectory()
val configFile = File(dir, "test-config.json")

FileInputStream(configFile).use {
    config = json.decodeFromStream(it)
}

存储目录获取的问题

  • 尝试获取测试context的外部文件目录,始终返回null(已确认外部存储已挂载):
instrumentation.context.getExternalFilesDir(null)
val dir = instrumentation.context.getExternalFilesDir(null)
  • 能获取到target context的外部文件目录:
instrumentation.targetContext.getExternalFilesDir(null)
val dir = instrumentation.targetContext.getExternalFilesDir(null)

但由于启用了Orchestrator且设置了clearPackageData: true,该目录会在测试实例化前被清空,无法读取文件。

官方文档相关疑问

看到Android官方文档中测试可选择退出存储限制的章节,但不确定如何通过测试runner配置,且我仅需读取数据而非写入,同时该配置会影响被测应用,还可能导致测试context的getExternalFilesDir(null)返回null。

请问是否有可行方案实现需求?还是只能将配置文件编译进测试APK,通过以下方式读取:

this::class.java.classLoader?.getResource("test-config.json")?.openStream()?.use {
    config = json.decodeFromStream(it)
}

内容的提问来源于stack exchange,提问作者Mark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 07:32:58