Search code examples
javareflectionjunitclassloaderdynamic-class-loaders

Run JUnit test programmatically loading different .class files


i'm currently able to run a JUnit test programmatically doing something like this:

JUnitCore junit = new JUnitCore();
Result result = new Result();

File root = new File("rootWhereSommatoreTest.classIS");
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[]{root.toURI().toURL() });
Class<?> cls = classLoader.loadClass("SommatoreTest");  
result = junit.run(cls);
return result;

What i dislike about this code is that SommatoreTest.class must be in the same directory as Sommatore.class to work. So i was wondering if it was possible to run a Junit test, loading separately .class files from different directories in the same ClassLoader, enabling SommatoreTest to "see" Sommatore.

Thanks in advance for your answer! And keep up the good work!


Solution

  • You simply need to make sure that the URL provided to your URLClassLoader matches with the root folder of your test class or with the jar file that contains your test class.

    In your case you seem to use a directory, so assuming that the FQN of your class is my.package.MyTest and the file MyTest.class is in the directory /my/class/dir/my/package, then you need to make sure that the URL will match with the root folder of your test class which will be in this case /my/class/dir/.