Android 测试用例的权限

Android permissions for a testcase

我正在为我的应用程序开发一个测试用例,它应该验证文件导入操作的正确性。为了自动测试它,我的计划是从我的测试资产目录中将一个文件复制到被测设备的下载文件夹中,然后使用 Espresso 测试用例执行导入操作。

有人有这方面的经验吗?我 运行 遇到了我的测试用例无权向设备写入任何内容的问题。

到目前为止,我已经为我的测试应用程序创建了一个包含所需权限的专用 manifest.xml 文件:

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

此外,我在测试开始之前执行此操作以向测试用例授予所需的权限:

adb shell pm grant com.my_app_pacakge.test android.permission.WRITE_EXTERNAL_STORAGE

不幸的是,当我在下载目录中创建文件时,在我尝试将内容写入备份文件时抛出以下异常:

Caused by: java.io.FileNotFoundException: /storage/emulated/0/Download/small_backup: open failed: EACCES (Permission denied)

相关代码如下:

public void putBackupFile(String name  ){
        File backupFile = new File(Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_DOWNLOADS ).getPath(), name );

        try {
            InputStream is = InstrumentationRegistry.getInstrumentation().getContext().getAssets().open( name );
            FileOutputStream fileOutputStream = new FileOutputStream(backupFile);

            byte[] buffer = new byte[1024];

            int len;

            while ((len = is.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, len);
            }

            fileOutputStream.close();
            is.close();
        } catch (IOException e1) {
            throw new RuntimeException(e1);
        }
    }

异常触发时间:FileOutputStream fileOutputStream = new FileOutputStream(backupFile);

我意识到我的问题中的方法状态不是最好的方法:我已经用另一种方式解决了这个问题:使用 adb 命令行传输所需的文件:

adb push small_backup /mnt/sdcard/Download

此语句集成在我的测试设置中(在 运行 测试之前执行)。在测试用例中,我想当然地认为所需的文件可用。

回答原始问题:如果您从 adb 授予 android.permission.WRITE_EXTERNAL_STORAGE,您还必须授予 android.permission.READ_EXTERNAL_STORAGE:

adb shell pm grant com.my_app_pacakge.test android.permission.READ_EXTERNAL_STORAGE

似乎如果有人在应用程序中请求 WRITE 权限,READ 权限会自动 asked/granted。如果从 adb 执行,则必须额外授予 READ 权限。