2016-05-14 18 views
3

我怎麼能在我的目錄訪問一個文本文件「的src /測試/資源」如何在Android中訪問用於JUnit測試的文本文件?

我不能似乎我的JUnit測試中得到它的皮卡

移動/的build.gradle:

sourceSets { 
     test { 
      java { 
       srcDirs = [ 'src/test/java' ] 
      } 
      resources { 
       srcDirs = [ 'src/test/resources' ] 
      } 
     } 
    } 

測試方法:

@Test 
public void test_file() { 
    URL resource = getClass().getResource("file_four_lines.txt"); 
    File file = new File(resource.getFile()); // Get NullPointerException here 
    ... 

} 

回答

3

/前綴文件路徑。

基本上,你會做這樣的事情:

File helloBleprintJson = new File(
     getClass().getResource("/helloBlueprint.json").getPath()); 

上面的代碼是從here拍攝。

+0

而且我也不需要修改build.gradle中的sourceSets。謝謝@rharter – Kamilski81

0

I think這個鏈接會有所幫助。在你的情況下,爲什麼不測試hard code字符串?爲什麼不使用String.xml而不是「file_four_lines.txt」。國際化需要具有不同語言,屏幕大小,方向,風味,夜間/日間視覺版本的每個資源文件的目錄結構。出於這個原因,資源從R文件編譯和訪問。您試圖通過使用.txt而不是.xml並直接訪問資源來繞過此慣例,它只是感覺錯誤。我認爲測試不像沒有遵循慣例那樣是個問題。

+0

謝謝。比方說,我想測試一個文件的輸入,並想從類路徑中獲取一個json文件......這不僅僅是文件系統上的一個文件。我的單元測試不需要本地化。 – Kamilski81

0

原諒我發表了兩遍,我的答案爲:from the official documentation「任意文件以原始格式保存要使用原始InputStream打開這些資源,請使用Resources.openRawResource()與資源ID(它是R. raw.filename。

但是,如果您需要訪問原始文件名和文件層次結構,則可以考慮在assets /目錄中保存一些資源(而不是res/raw /)。資源ID,因此只能使用AssetManager讀取它們。「 Json和txt are non-standard(unsupported),所以你必須提供你自己的實現/ parcer來讀取這個類型的文件。感謝這篇文章。我知道關於資源的一些事情,但是現在感謝你的刺激,我知道更多。回顧The Android resource system keeps track of all non-code assets associated with an application. The Android SDK tools compile your application's resources into the application binary at build time. To use a resource, you must install it correctly in the source tree (inside your project's res/ directory) and build your application. As part of the build process, the SDK tools generate symbols for each resource, which you can use in your application code to access the resources,當然所提到的符號在生成的R文件中

相關問題