Access to resources in unit tests

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

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'm reading, this should give me access to the resource file. However, I get a null pointer exception when trying to use the URL because calling getSystemResource() returns null.

How to access my resource files?

+7
java junit4 gradle
source share
2 answers

Resource names do not start with a slash, so you need to get rid of them. Preferably, the resource is read using UnitTests.getClassLoader().getResourceAsStream("the/resource/name") or, if File is required, new File(UnitTests.getClassLoader().getResource("the/resource/name").toURI()) .

In Java 8, you can 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")); 
+12
source share

I think you want getResource instead of getSystemResource. The latter is used, for example, to read a file from the file system, where the path will not be specified in terms of banks.

You can also skip the class loader: UnitTests.class.getResource("...")

Resource docs here

Edit : There are more detailed comments in the answers here .

0
source share

All Articles