访问单元测试中的资源

kwi*_*ver 9 java junit4 gradle

我正在使用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();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

根据我的阅读,这应该让我访问资源文件.但是,当我尝试使用URL时,我得到一个空指针异常,因为该getSystemResource()调用返回null.

如何访问我的资源文件?

Pet*_*ser 15

资源名称不以斜杠开头,因此您需要摆脱它.优选地UnitTests.getClassLoader().getResourceAsStream("the/resource/name"),应该使用,或者如果File需要,则读取资源new File(UnitTests.getClassLoader().getResource("the/resource/name").toURI()).

在Java 8上,您可以尝试以下方法:

URI uri = UnitTests.class.getClassLoader().getResource("the/resource/name").toURI();
String string = new String(Files.readAllBytes(Paths.get(uri)), Charset.forName("utf-8"));
Run Code Online (Sandbox Code Playgroud)