Static resource files not found from from test code via gradle


(ric) #1

I have unit-test code that needs to read a json data file to get some test data to use as input for my test.

My project is multi-module, and follows the standard layout for java project (i.e., maven default layout). My json data file is in the “resources” folder under my “test” folder, and in my unit-test class I have code like this to read it:

Path path = Paths.get("core/build/resources/test/test.json");
assertNotNull(path);

I can see that test.json does exist in that folder, but when I run “gradlew build” or “gradlew test” this code fails with: “java.nio.file.NoSuchFileException: core\build\resources\test\test.json”

However, in IntelliJ, if I right-click the unit-test class and select “run”, the file is found and the test succeeds.

I skeleton project that exhibits this behavior here:

https://github.com/ricpdx/skeleton.git

Can you spot the flaw in my configuration that makes gradle unable to find the file even while IntelliJ can find it? Both are reading it from the same place.

Finally, zooming out for a minute, is there a better way to read static resource files - something that will work at both runtime and test-time? It would probably be better if my code didn’t have to know the details of the path.

Thanks.


(Peter Niederwieser) #2

The code is using a relative path, which makes it depend on the current working directory of the JVM that launches the tests. A more reliable way to read resource files is ‘getClass().getClassLoader().getResourceAsStream()’, or, if necessary, ‘getClass().getClassLoader().getResource()’. In a J2EE environment you’d typically use ‘Thread.currentThread().getContextClassLoader().getResourceAsStream()’.


(ric) #3

That got it. Thanks.

I’m using getClass().getClassLoader().getResourceAsStream() now, but I understand I will have to change to Thread.currentThread().getContextClassLoader().getResourceAsStream() when running from an application server.


(ric) #4

That got it. Thanks.

I’m using getClass().getClassLoader().getResourceAsStream() now, but I understand I will have to change to Thread.currentThread().getContextClassLoader().getResourceAsStream() when running from an application server.