Wrong resource url when using URLClassloader to load test classes and run junit tests

172 Views Asked by At

I have two maven projects.

Project 1: Used to load junit tests classes of project 2 and use junit APIs to programatically execute test cases.

String[] classAndMethodNames = ["packageName.Classname","Methodname"];
LauncherDiscoveryRequestBuilder requestBuilder = LauncherDiscoveryRequestBuilder.request();
requestBuilder.selectors(selectMethod(urlClassLoader.loadClass(classAndMethodNames[0]), classAndMethodNames[1]));

Project 2: https://github.com/apache/commons-csv/blob/master/src/test/java/org/apache/commons/csv/issues/JiraCsv248Test.java

Project 2 loads this class and runs the test org.apache.commons.csv.issues#testJiraCsv248.

The Problem : This test reads a file using a ClassLoader.getSystemClassLoader().getResourceAsStream(), now the expected path of this file should be in reference to the Project 2 test class(Project2DIR/filepath), But actually it is Project1/filepath.

Is there any way in which this path can be corrected.

1

There are 1 best solutions below

0
cyberbrain On

You probably should consult the Javadoc of ClassLoader.getSystemClassLoader() but in general your approach with the correct URL will not really help you, because a classloader doesn't have to be resolving URLs always.

You could try two approaches:

  1. Set the classpath on the execution of project 1 in a way that the test resources of project 1 will be found before anything from project 2
  2. Set the system property java.system.class.loader to your own implementation of ClassLoader that has special handling for the resources for project 1 and delegates anything else to the real system classloader. This is a very hacky solution, so I would prefer #1

For #2, you should set the system property just before you load the first class of project 1, and save the original system classloader before so you can properly delegate all the non-test-resource requests.