Thursday, August 10, 2017

Proper way to access file resources in junit tests

Proper way to access file resources in junit tests


As I was refactoring some JUnit tests recently I was reminded of an important fact on the proper way to read in a file.
In maven any file under /src/test/resources is automatically copied over to /target/test-classes. So for example lets say I need to read in a wsdl in my test. So I place the wsdl in the resources folder: /src/test/resources/test.wsdl. Now at first it might be tempting to reference the file with the following code:

File testWsdl = new File("/src/test/resources/test.wsdl");

and this will actually work on a windows machine; but what about linux, cygwin, or even solaris. Your next improvement might be to replace the / with File.separator:

File testWsdl = new File(File.separator + "src" + File.separator + "test"
    + File.separator + "resources" + File.separator + "test.wsdl");

This still isnt the best solution which is presented below:

URL url = this.getClass().getResource("/test.wsdl");
File testWsdl = new File(url.getFile());


Using the classs resource will locate the file in the tests classpath, which happens to be /target/test-classes. And this final solution will work on windows, linux, cygwin, and solaris.

Available link for download