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 isn’t the best solution which is presented below:

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

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

Spring ResourceLoader

if it is in the context of Spring we can
    private ResourceLoader resourceLoader;

The benefit of this is for testing, we could mock the ResourceLoader and get mock resources.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s