Integration with Build Tools

Integration of TestNG with build tools like Apache Maven and Gradle is a common practice in Java test automation. It allows you to manage dependencies, build and run your TestNG tests as part of your project's build process. It is an important step towards CI/CD. Here's how to integrate TestNG with Maven:


Integration with Maven:

1. Create a Maven Project:

If you don't have a Maven project already, create one using your IDE or the command line. You can refer chapter Environment Setup for how to create maven project.

2. Create a TestNGTest.java:

Java
Copy
package org.example;

import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class ExampleTest {
    @Test
    public void ExampleTest1Method1()
    {
        System.out.println("ExampleTest1Method1");
    }
    @Test
    public void ExampleTest1Method2()
    {
        System.out.println("ExampleTest1Method2");
    }
}

2. Create a suite file testng.xml:

XML
Copy
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Example Suite">
    <test name="Example Test">
        <classes>
            <class name="org.example.ExampleTest"/>
        </classes>
    </test>
</suite>

3. Configure the Surefire Plugin:

Maven uses the Surefire Plugin to run tests. The Surefire Plugin should be configured correctly in your pom.xml file. The configuration typically goes in the section. Below xml file is a sample configuration.

XML
Copy
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M5</version> <!-- Use an appropriate version -->
            <configuration>
                <suiteXmlFiles>
                    <suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
                </suiteXmlFiles>
            </configuration>
        </plugin>
    </plugins>
</build>

4. Run Tests:

You can now run your TestNG tests using the Maven command:

mvn test

When you run the above command, you should below result in the log.


ExampleTest1Method1
ExampleTest1Method2
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.183 s - in TestSuite
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------