Skip to content
Advertisement

How to get the path of src/test/resources directory in 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?

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement