stackoverflow stackoverflow - 11 days ago 7
Java Question

How to use maven test classes in main class

I am trying to create a test automation framework using Maven and TestNG. All the test classes in the application are written under

src/test/java
folder and all utility methods are written under
src/main/java
. I can run all the test scripts using
pom.xml
successfully. The framework also contains a main method from where
testng.xml
is created dynamically and the test classes are run. In the main method I am loading the test classes using below code

File classDir = new File("C:/workspace/myproject/target/test-classes/packagename/testScripts/"); //This is the path of all the compiled test classes
URL[] classUrl = {classDir.toURI().toURL()};
URLClassLoader urlClassLoader = new URLClassLoader(classUrl);
Class<?> testClass=urlClassLoader.loadClass("packagename.testScripts.TestClassName");


but it throws exception

java.lang.ClassNotFoundException: packagename.testScripts.TestClassName


How to resolve this issue?

Answer

According to the FQN of your class which is packagename.testScripts.TestClassName, your classDir is not properly set it should rather be:

File classDir = new File("C:/workspace/myproject/target/test-classes/");