TestNG Official Documentation on Programattic Execution
If you are looking to run your tests programmatically, it's best to read an existing testng XML file, do some runtime modifications and run it programmatically. This would basically avoid the problem of hardcoding class names and test names in the code. If you are hardcoding test names and class names, then you would need to change the test names and class names every time you need to run a different case. So please avoid hardcoding. Please follow the below approach, it would suit your need.
List<String> deviceNames = StringUtils.isEmpty(System.getProperty("deviceNames")) ?
new ArrayList<>() : Arrays.asList(System.getProperty("deviceNames").split(","));
TestNG tng = new TestNG();
File initialFile = new File("testng.xml");
InputStream inputStream = FileUtils.openInputStream(initialFile);
Parser p = new Parser(inputStream);
List<XmlSuite> suites = p.parseToList();
List<XmlSuite> modifiedSuites = new ArrayList<>();
for (XmlSuite suite : suites) {
XmlSuite modifiedSuite = new XmlSuite();
modifiedSuite.setParallel(suite.getParallel());
modifiedSuite.setThreadCount(deviceNames.size());
modifiedSuite.setName(suite.getName());
modifiedSuite.setListeners(suite.getListeners());
List<XmlTest> tests = suite.getTests();
for (XmlTest test : tests) {
for (int i = 0; i < deviceNames.size(); i++) {
XmlTest modifedtest = new XmlTest(modifiedSuite);
HashMap<String, String> parametersMap = new HashMap<>();
parametersMap.put("deviceName", deviceNames.get(i));
modifedtest.setParameters(parametersMap);
modifedtest.setName(test.getName() + "Device - " + deviceNames.get(i) +
", OS Version - " + platformVersions.get(i));
modifedtest.setXmlClasses(test.getXmlClasses());
}
}
modifiedSuites.add(modifiedSuite);
}
inputStream.close();
tng.setXmlSuites(modifiedSuites);
tng.run();
I am adding runtime parameters to each and every test based on the parameters passed in the maven runtime arguments. You could use the same approach for passing test names or class names as runtime arguments and update your testng XML file as per your need.