2013-01-14 29 views
5

我正在使用InstrumentationTestCase單元測試我的應用程序的一個組件。Android InstrumentationTestCase getFilesDir()返回null

該組件將數據保存到內部存儲並使用Context::fileList();來檢索持久保存的文件。

我遇到以下問題:在應用程序中使用此方法(在設備上)工作得很好。但是當我嘗試使用InstrumentationTestCase進行(Android-)單元測試(同樣在設備上)時,我在fileList()方法中得到了NullPointerException。我深入瞭解了android源代碼,發現getFilesDir()(see source here)返回null並導致此錯誤。

的代碼重現如下:

public class MyTestCase extends InstrumentationTestCase 
{ 
    public void testExample() throws Exception 
    { 
     assertNotNull(getInstrumentation().getContext().getFilesDir()); // Fails 
    } 
} 

我的問題是:這種行爲是故意的嗎?我能做些什麼來規避這個問題?我是否正確使用InstrumentationTestCase或者我應該使用不同的東西?

我發現this question但我不確定這是否覆蓋了我所遇到的同樣的問題。

+0

您是否嘗試使用getTargetContext()而不是getContext() – Blackbelt

+0

嗯,是的。 'getTargetContext()'按預期工作,但我希望獨立於應用程序運行測試(或多或少)。這就是我選擇'InstrumentationTestCase'的原因。 – GeneSys

+0

正如名稱所述,InstrumentationTestCase是一個工具測試,通過使用第二個測試應用程序來測試用於測試Android組件的主應用程序,例如活動正確渲染或正確處理用戶交互。獨立於主應用運行測試應用程序沒有多大意義。 – yorkw

回答

10

我認爲你保持測試數據與測試應用程序分開是正確的。

您可以Null創建files目錄Instrumentation應用程序通過執行以下命令

adb shell 
cd /data/data/<package_id_of_instrumentation_app> 
mkdir files 

你能做到以上只在模擬器或植根設備解決問題​​。

然後從你的問題測試不會失敗。我做到了,還上載的文件名爲tst.txtfiles目錄,所有下面的測試是成功的:

assertNotNull(getInstrumentation().getContext().getFilesDir()); 
assertNotNull(getInstrumentation().getContext().openFileInput("tst.txt")); 
assertNotNull(getInstrumentation().getContext().openFileOutput("out.txt", Context.MODE_PRIVATE)); 

但我認爲把數據提供給測試項目更方便的方法是使用assets測試項目,在那裏你可以簡單地保存一些文件並打開它們:

assertNotNull(getInstrumentation().getContext().getAssets().open("asset.txt")); 

,或者如果你想測試的一些結果保存到文件,你可以使用ExternalStorage

File extStorage = Environment.getExternalStorageDirectory(); 
assertNotNull(extStorage); 
+1

+1不錯的一個。 shell修復允許我單元測試基於Realm.io的數據持久性。 –

+1

爲什麼文件目錄不在第一位? – JohnyTex