2012-05-10 25 views
2

創建文件,我想創建在Android JUNIT測試用例上建立一個文件:Android中的JUnit

protected void setUp() throws Exception { 
     super.setUp(); 

     File storageDirectory = new File("testDir"); 
     storageDirectory.mkdir(); 

     File storageFile = new File(storageDirectory.getAbsolutePath() 
       + "/test.log"); 

     if (!storageFile.exists()) { 
      storageFile.createNewFile(); 
     } 
     mContext = new InternalStorageMockContext(storageFile); 
     mContextWrapper = new ContextWrapper(mContext); 
    } 

我得到一個異常沒有這樣的文件或目錄當我打電話createNewFile。有沒有從Android JUNIT創建文件的標準方法?

回答

6

在Android中,目錄/文件的創建和訪問通常由Context進行管理。舉例來說,這通常是我們如何創造條件,應用程序的內部存儲目錄下的文件:

File testDir = Context.getDir("testDir", Context.MODE_PRIVATE); 

退房的API,還有很多其他有用的方法getXXXDir(),您可以用來創建/訪問文件。

回到JUnit的話題,假設你使用ActivityInstrumentationTestCase2和應用程序的項目有包名com.example,並且您的測試項目有包名com.example.test

// this will create app_tmp1 directoryunder data/data/com.example.test/, 
// in another word, use test app's internal storage. 
this.getInstrumentation().getContext().getDir("tmp1", Context.MODE_PRIVATE); 

// this will create app_tmp2 directory under data/data/com.example/, 
// in another word use app's internal storage. 
this.getInstrumentation().getTargetContext().getDir("tmp2", Context.MODE_PRIVATE); 

希望這有助於。