Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Resources in Unit Tests

I'm using JUnit 4, Java 8, and Gradle 1.12. I have a file with default json that I need to load. My project has src/main/java/ (containing the project source), src/main/resources/ (empty), src/test/java/ (unit test source), and src/test/resources/ (the json data file to load) directories. The build.gradle file is in the root.

In my code I have:

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();
    }
  }
}

From what I read, that should give me access to the resource file. However, I get a null pointer exception when I try to use the URL, because the getSystemResource() call returns null.

How do I access my resource files?

like image 924
kwiqsilver Avatar asked Jun 30 '14 22:06

kwiqsilver


1 Answers

Resource names don't start with a slash, so you'll need to get rid of that. The resource should preferably be read with UnitTests.getClassLoader().getResourceAsStream("the/resource/name"), or, if a File is required, new File(UnitTests.getClassLoader().getResource("the/resource/name").toURI()).

On Java 8, you could try something like:

URI uri = UnitTests.class.getClassLoader().getResource("the/resource/name").toURI();
String string = new String(Files.readAllBytes(Paths.get(uri)), Charset.forName("utf-8"));
like image 68
Peter Niederwieser Avatar answered Sep 28 '22 19:09

Peter Niederwieser