How to get a test resource file?

94,943

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");

Solution 4

// assuming a file src/test/resources/some-file.csv exists:

import java.io.InputStream;
// ...
InputStream is = getClass().getClassLoader().getResourceAsStream("some-file.csv");

Solution 5

import org.apache.commons.io.FileUtils;
...
 final File dic = FileUtils.getFile("src","test", "resources", "csvFile");

since Apache Commons IO 2.1.

Share:
94,943
simpatico
Author by

simpatico

Author of dp4j.jar, which lets you test access private methods in Java without writing any reflection API code. The necessary reflection code is injected by dp4j at compile-time. So you only write: @Test public void aTest(){ PrivateConstructor pc = new PrivateConstructor("Hello!"); Instead of: import java.lang.reflect.*; @Test public void aTest() throws IllegalAccessException, NoSuchMethodException , InvocationTargetException, InstantiationException { Constructor pcInit = PrivateConstructor.class.getDeclaredConstructor(String.class); pcInit.setAccessible(true); PrivateConstructor pc = (PrivateConstructor) pcInit.newInstance("Hello!"); Check it out at www.dp4j.com

Updated on November 30, 2020

Comments

  • simpatico
    simpatico over 3 years

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