How to get a test resource file?

In a unit test I need to import a csv file. This is located in the resources folder, i.e. src/test/resources


Solution 1:

Probably just useful if you have the file available, for example when doing unit tests - this will not load it out of a jar AFAIK.

URL url = Thread.currentThread().getContextClassLoader().getResource("mypackage/YourFile.csv");
File file = new File(url.getPath());
// where the file is in the classpath eg. <project>/src/test/resources/mypackage/YourFile.csv

Solution 2:

You can access test resources using the current thread's classloader:

InputStream stream = Thread.currentThread().getContextClassLoader()
    .getResourceAsStream("YOURFILE.CSV");

Solution 3:

with guava

import com.google.common.io.Resources;
URL url = Resources.getResource("YourFile.csv");