Reputation: 1194
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.
Upvotes: 3
Views: 3735
Reputation: 166
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/
Upvotes: 0
Reputation: 1348
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.
Upvotes: 3