How to get a test resource file?

JavaTestingResourcesMavenSurefire

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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 - Java

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

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

Solution 3 - Java

with guava

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

Solution 4 - Java

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

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

Solution 5 - Java

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

since Apache Commons IO 2.1.

Solution 6 - Java

This solution need not lib's. First create a util class to access the resource files.

public class TestUtil(Class classObj, String resourceName) throws IOException{
   URL resourceUrl = classObj.getResource(FileSystems.getDefault().getSeparator()+resourceName);
   assertNotNull(resourceUrl);
   return new File(resourceUrl.getFile());
}

Now you just need to call the method with the class of your unitTest and the name of your file in the ressource folder.

File cvsTestFile = TestUtil.GetDocFromResource(getClass(), "MyTestFile.cvs");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsimpaticoView Question on Stackoverflow
Solution 1 - JavaAmanicAView Answer on Stackoverflow
Solution 2 - JavaRuss HaywardView Answer on Stackoverflow
Solution 3 - JavaDavid Michael GangView Answer on Stackoverflow
Solution 4 - JavaAbdullView Answer on Stackoverflow
Solution 5 - JavasimpaticoView Answer on Stackoverflow
Solution 6 - JavaswissonidView Answer on Stackoverflow