In a unit test I need to import a csv file. This is located in the resources folder, i.e. src/test/resources
How to get a test resource file?
Found simple solution (Java7+) here : https://mcmap.net/q/98178/-how-to-get-the-path-of-src-test-resources-directory-in-junit –
Leroi
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
what I was really looking for was abstraction from providing the path to the file, as in getResourceAsStream. Otherwise new File/getFile is more straightforward –
Decant
url is null for me with that statement –
Doura
@Doura ok fixed my answer, the path you specify is actually relative to the classpath, so you should leave out the
src/test/resources
part. (getResource returns null if it can't find the file) –
Renaterenato the resolution of the file ends up including the package of the current class. @Doura –
Cellulitis
Need to use
new File(url.toURI());
to correctly handle spaces in file path. –
Unlawful You can access test resources using the current thread's classloader:
InputStream stream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("YOURFILE.CSV");
but I want a java.io.File and not an InputStream. –
Decant
then use getClass().getResource("/src/test/resources/YourFile.csv"); download.oracle.com/javase/6/docs/api/java/lang/Class.html –
Awake
so, FileUtils.toFile(Thread.currentThread().getClass().getResource("/src/test/resources/YourFile.csv")); –
Decant
with guava
import com.google.common.io.Resources;
URL url = Resources.getResource("YourFile.csv");
as @Decant wants a
java.io.File
, this answer can go on with: File csvFile = new File( url.toURI() );
–
Kc // assuming a file src/test/resources/some-file.csv exists:
import java.io.InputStream;
// ...
InputStream is = getClass().getClassLoader().getResourceAsStream("some-file.csv");
import org.apache.commons.io.FileUtils;
...
final File dic = FileUtils.getFile("src","test", "resources", "csvFile");
since Apache Commons IO 2.1.
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");
where can I get FileSystems class ? –
Liquor
@ToKra java.nio.file.FileSystems –
Burglary
© 2022 - 2024 — McMap. All rights reserved.