Introduction to TestNG
Introduction to TestNG
TestNG (Test Next Generation) is a powerful testing framework for Java that is inspired by JUnit
but provides additional functionalities, such as annotations, parallel execution, and flexible test
configurations. It is widely used for automation testing, especially with Selenium.
Installation To use TestNG in a Maven project, add the following dependency to your pom.xml:
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.8.0</version>
<scope>test</scope>
</dependency>
</dependencies>
If using Eclipse, you can install TestNG from the Eclipse Marketplace.
Basic TestNG Example Create a Java class and use TestNG annotations to define test cases:
import org.testng.annotations.Test;
@Test
public void testMethod() {
System.out.println("TestNG test executed successfully!");
}
}
To run this test, right-click the file and select Run As → TestNG Test.
TestNG Annotations
• @Test: Marks a method as a test case.
• @BeforeSuite: Runs before all test cases in a suite.
• @AfterSuite: Runs after all test cases in a suite.
• @BeforeClass: Runs before any test method in the class.
• @AfterClass: Runs after all test methods in the class.
• @BeforeMethod: Runs before each test method.
• @AfterMethod: Runs after each test method.
• @DataProvider: Provides data-driven testing.
Example:
import org.testng.annotations.*;
@BeforeMethod
public void setup() {
System.out.println("Setup before each test");
}
@Test
public void test1() {
System.out.println("Executing Test 1");
}
@Test
public void test2() {
System.out.println("Executing Test 2");
}
@AfterMethod
public void teardown() {
System.out.println("Teardown after each test");
}
}
TestNG XML Configuration You can use a testng.xml file to define and manage test
execution:
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="Test">
<classes>
<class name="TestExample"/>
</classes>
</test>
</suite>
Run it using:
mvn test
This guide provides a basic introduction, but you can explore more features like listeners,
assertions, and test dependencies in the official TestNG documentation at testng.org.