How do I create a TestNG XML file?

How do I create a TestNG XML file?

Hi Dipen,

A TestNG XML file is created by defining a suite, specifying tests, and identifying the classes and methods to run. This file is used to configure and manage TestNG test runs.

You can check out this blog for more details:

Hey Dipen,

Programmatically Generating TestNG XML :

Steps: Use TestNG API: Use the TestNG XmlSuite, XmlTest, and XmlClass classes to generate the XML file programmatically. Write to File: Generate and write the XML content to a file.

import org.testng.xml.XmlClass; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest;

import java.util.Collections;

public class GenerateTestNGXML { public static void main(String[] args) { XmlSuite suite = new XmlSuite(); suite.setName(“SuiteName”);

    XmlTest test = new XmlTest(suite);
    test.setName("TestName");

    XmlClass testClass1 = new XmlClass("com.example.tests.TestClass1");
    XmlClass testClass2 = new XmlClass("com.example.tests.TestClass2");
    test.setXmlClasses(Collections.asList(testClass1, testClass2));

    // Save to XML file
    try (FileWriter writer = new FileWriter(new File("testng.xml"))) {
        writer.write(suite.toXml());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

Explanation:

Create an XmlSuite object for the suite. Create an XmlTest object for each test and add it to the suite. Create XmlClass objects for each test class and add them to the test. Write the generated XML content to a file.