2

我正在爲我的應用程序測試一個文件導入操作的正確性。爲了自動測試,我的計劃是將我的測試資產目錄中的文件複製到被測設備的下載文件夾中,並使用Espresso測試用例執行導入操作。測試用例的Android權限

有人有這方面的經驗嗎?我遇到了這樣一個問題,即我的測試用例沒有權限向設備寫入任何內容。

到目前爲止,我已經創建了一個專門的manifest.xml文件包含所需的權限我的測試應用程序:

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

而且,我在執行此操作前我的測試開始給予必要的許可權測試用例:

012:

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);

+0

發佈您創建文件的代碼。因爲它可能是您嘗試將路徑應用於文件的問題。 – JoxTraex

+0

更改了帖子以包含相關代碼 – Peter

+0

您是否嘗試在應用程序中包含權限?我想我曾經有一個類似的問題,其中測試應用程序只能使用應用程序的權限 –

回答

0

回答原來的問題:如果從亞洲開發銀行授予android.permission.WRITE_EXTERNAL_STORAGE,你必須給予android.permission.READ_EXTERNAL_STORAGE還有:

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

這似乎是,如果一個人要求寫在應用程序中的權限,自動詢問/授予讀取權限。如果從adb中進行,則必須另外授予READ權限。

0

我意識到,在我的問題的appraoch狀態不是最好的辦法:我已經解決了這個另一種方法:使用adb命令行傳輸所需文件:

adb push small_backup/mnt/sdcard/Download

該聲明已集成到我的測試設置中(在運行測試之前執行)。在測試案例中,我認爲所需的文件是可用的。