Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't access files from src/main/resources via a test-case

I have a file.dat in src/main/resources.

When I try to test a class which loads this file via a jar file, the test fails because its not able to find the file in the path (I/O Exception). The path which I get via test is:

/home/usr/workspace/project/target/test-classes/file.dat

but the file is not exist in target/test-classes any idea?

like image 404
tokhi Avatar asked Sep 18 '13 14:09

tokhi


People also ask

How to read a file from src test resources in java?

The simplest approach uses an instance of the java. io. File class to read the /src/test/resources directory by calling the getAbsolutePath() method: String path = "src/test/resources"; File file = new File(path); String absolutePath = file.

How to get file from test resources folder in java?

In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass(). getClassLoader().

How do I create a resource SRC test?

Right click on maven project --->Click on Build Path ----->Click on New Source Folder. New source folder window will open, give the name to your folder example - src/test/source. click on Finish.

What is the path of resource folder in Java?

The resources folder belongs to the maven project structure where we place the configuration and data files related to the application. The location of the folder is “ src/main/resources “.


Video Answer


2 Answers

Files from src/main/resources will be available on the classpath during runtime of the main program, while files both from src/main/resources and src/test/resources will be available on the classpath during test runs.

One way to retrieve files residing on the classpath is:

Object content = Thread.currentThread().getContextClassLoader().getResource("file.dat").getContent();

.. where the type of content depends on the file contents. You can also get the file as an InputStream:

InputStream contentStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("file.dat");
like image 74
Jonas Berlin Avatar answered Sep 19 '22 13:09

Jonas Berlin


If the file is in

src/main/resources/file.dat

You can get the URL to the file :

getClass().getResource("/file.dat");

like image 20
Georgi Eftimov Avatar answered Sep 20 '22 13:09

Georgi Eftimov