Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the path of src/test/resources directory in JUnit?

Tags:

java

junit

I know I can load a file from src/test/resources with:

getClass().getResource("somefile").getFile() 

But how can I get the full path to the src/test/resources directory, i.e. I don't want to load a file, I just want to know the path of the directory?

like image 983
Rory Avatar asked Feb 23 '15 12:02

Rory


People also ask

Where do you put test resources?

what is a resource? a resource is a file in the class path folder structure for your project. this is important because your test resources will be put in your test-classes folder hierarchy and your main resources will be put in your classes folder hierarchy — both in your target folder.

How do I read a file from SRC main resources?

Using Java getResourceAsStream() This is an example of using getResourceAsStream method to read a file from src/main/resources directory. First, we are using the getResourceAsStream method to create an instance of InputStream. Next, we create an instance of InputStreamReader for the input stream.

How do I add resources to 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 classpath resource in Java?

Classpath in Java is not only used to load . class files, but also can be used to load resources e.g. properties files, images, icons, thumbnails, or any binary content. Java provides API to read these resources as InputStream or URL.


Video Answer


2 Answers

You don't need to mess with class loaders. In fact it's a bad habit to get into because class loader resources are not java.io.File objects when they are in a jar archive.

Maven automatically sets the current working directory before running tests, so you can just use:

    File resourcesDirectory = new File("src/test/resources"); 

resourcesDirectory.getAbsolutePath() will return the correct value if that is what you really need.

I recommend creating a src/test/data directory if you want your tests to access data via the file system. This makes it clear what you're doing.

like image 191
Steve C Avatar answered Oct 02 '22 20:10

Steve C


Try working with the ClassLoader class:

ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource("somefile").getFile()); System.out.println(file.getAbsolutePath()); 

A ClassLoader is responsible for loading in classes. Every class has a reference to a ClassLoader. This code returns a File from the resource directory. Calling getAbsolutePath() on it returns its absolute Path.

Javadoc for ClassLoader: http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html

like image 35
ashosborne1 Avatar answered Oct 02 '22 20:10

ashosborne1