How to get the path of src/test/resources directory in JUnit?
In JUnit, you can use the getClass().getClassLoader().getResource("").getPath() method to get the path of the src/test/resources directory.
In JUnit, you can use getClass().getClassLoader().getResource("") to get the path to the test classes root directory (typically target/test-classes in Maven or build/classes/java/test in Gradle), which contains your compiled src/test/resources files.
Here is an example of how to use this method to get the path:
import org.junit.Test;
import java.io.File;
public class MyTest {
@Test
public void test() {
String path = getClass().getClassLoader().getResource("").toURI().getPath();
System.out.println(path);
}
}This will print the path to the console.
Alternatively, you can use ClassLoader.getSystemClassLoader().getResource("") to achieve the same result:
import org.junit.Test;
public class MyTest {
@Test
public void test() {
String path = ClassLoader.getSystemClassLoader().getResource("").toURI().getPath();
System.out.println(path);
}
}This will also print the path to the console.
You can then use this path to access files in the compiled resources directory. For example, you can use the java.io.File class to construct a path to a specific file:
File file = new File(path + "example.txt");