Get full path of a package situated in source folder from junit

3.6k views Asked by At

I have used below code in my junit to get the directory of my package.

String pkgname = "com.acn.omi.util";
String relPath = pkgname.replace('.', '/');
URL resource = ClassLoader.getSystemClassLoader().getResource(relPath);

But this code search for package in target/test-classes folder which contain classes from src/test/java source folder so it is not able to find the package situated in my source folder(src/main/java).

How can i get the file situated in a package from junit.

My purpose is to load all the classes from that folder and modify their field using reflection.

2

There are 2 answers

0
Alexandr Radchykov On

You can try to write like this

URL resource = User.class.getProtectionDomain().getCodeSource().getLocation()

In my case class "User" is placed in target package, so I've output it tests like this:

file:.../target/classes/
5
Kalyan Chavali On

You can try to fetch the classes location using the below code

String pkgname = "com.acn.omi.util";
    String relPath = pkgname.replace('.', '\\');
    String workingDirectory = System.getProperty("user.dir");
    String requiredDirectory = workingDirectory + "\\" + "src\\test\\java"
            + relPath;
    URL resource = ClassLoader.getSystemClassLoader().getResource(
            requiredDirectory);

This will fetch you the complete location to the test classes.