我正在使用JUnit 4,Java 8和Gradle 1.12。 我有我需要加載的默認json文件。我的項目有src/main/java/
(包含項目源),src/main/resources/
(空),src/test/java/
(單元測試源)和src/test/resources/
(要加載的json數據文件)目錄。 build.gradle
文件位於根目錄中。訪問單元測試資源
在我的代碼有:
public class UnitTests extends JerseyTest
{
@Test
public void test1() throws IOException
{
String json = UnitTests.readResource("/testData.json");
// Do stuff ...
}
// ...
private static String readResource(String resource) throws IOException
{
// I had these three lines combined, but separated them to find the null.
ClassLoader c = UnitTests.class.getClassLoader();
URL r = c.getSystemResource(resource); // This is returning null. ????
//URL r = c.getResource(resource); // This had the same issue.
String fileName = r.getFile();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName)))
{
StringBuffer fileData = new StringBuffer();
char[] buf = new char[1024];
int readCount = 0;
while ((readCount = reader.read(buf)) != -1)
{
String readData = String.valueOf(buf, 0, readCount);
fileData.append(readData);
}
return fileData.toString();
}
}
}
從我讀,應該給我訪問的資源文件。但是,當我嘗試使用URL時,我得到空指針異常,因爲getSystemResource()
調用返回null。
如何訪問我的資源文件?
你有在類路徑中/ src目錄/測試/資源文件夾? –
我對此表示懷疑。雖然我沒有加載類。 – kwiqsilver