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

南笙酒味 提交于 2019-11-28 10:27:49

I used the following in my main() method and it worked.

    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();

You can load your usual xml in main using 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();
}

If that is your folder structure, and not just a type, it's wrong. The package name is represented as a folder structure, not one folder with the package name.

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

Also, make sure your test classes are actually in the Jar file. If you're using maven to build the Jar, your test classes will not be included by default.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!