How to run TestNG tests from main () in an executable jar?

I have an executable JAR that contains all the dependencies and test classes. I confirmed that the main () method is called when the jar is executed. I am trying to add code to main () so that I can run a specific TestNG test class. From the documentation on TestNG.org, this seems to be the way to do this:

TestListenerAdapter tla = new TestListenerAdapter(); TestNG testng = new TestNG(); testng.setTestClasses(new Class[] { com.some.path.tests.MyTests.class }); testng.addListener(tla); testng.run(); 

My folder structure is typical:

  /src/main/java/Main.java /src/test/java/com/some/path/tests/MyTests.java 

However, when I try to compile it, I get this error:

  java: /src/main/java/Main.java:46: package com.some.path.tests does not exist 

Anyway, can I change my project so that testng.setTestClasses () in main () can access the test class?

+2
java jar unit-testing executable-jar testng
source share
3 answers

In my main () method, I used the following:

  CommandLineOptions options = new CommandLineOptions(); JCommander jCommander = new JCommander(options, args); XmlSuite suite = new XmlSuite(); suite.setName("MyTestSuite"); suite.setParameters(options.convertToMap()); List<XmlClass> classes = new ArrayList<XmlClass>(); classes.add(new XmlClass("com.some.path.tests.MyTests")); XmlTest test = new XmlTest(suite); test.setName("MyTests"); test.setXmlClasses(classes); List<XmlSuite> suites = new ArrayList<XmlSuite>(); suites.add(suite); TestNG testNG = new TestNG(); testNG.setXmlSuites(suites); testNG.run(); 
+4
source share

You can load your regular xml mainly with org.testng.xml.Parser and org.testng.xml.XmlSuite

 String xmlFileName = "testng.xml"; List<XmlSuite> suite; try { suite = (List <XmlSuite>)(new Parser(xmlFileName).parse()); testng.setXmlSuites(suite); testng.run(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } 
+5
source share

If this is your folder structure and not just a type, this is wrong. The package name is represented as a folder structure, not a single folder with the package name.

So this should be src/test/java/com/some/path/tests/MyTests.java

Also, make sure your test classes are in the Jar file. If you use maven to create a Jar, your test classes will not be included by default.

+1
source share

All Articles