Below are the steps and code to integrate TestNG with Selenium in Java.
What is TestNG?
TestNG (Test Next Generation) is a testing framework inspired by JUnit and NUnit. It is designed to make testing easier and more powerful with:
Annotations (@Test, @BeforeMethod, @AfterMethod, etc.)
Grouping test cases
Parallel execution
XML-based configuration
Data-driven testing
Steps to Integrate TestNG with Selenium Java
Install TestNG Plugin in Eclipse
Go to Help > Eclipse Marketplace
Search for TestNG, install, and restart Eclipse
Add Selenium and TestNG Dependencies in pom.xml
<dependencies> <!-- Selenium --> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.21.0</version> </dependency> <!-- TestNG --> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.9.0</version> <scope>test</scope> </dependency> </dependencies>
Write TestNG Test Class with Selenium Code
Example Code
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class GoogleSearchTest { WebDriver driver; @BeforeClass public void setup() { // Set path to chromedriver System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); driver = new ChromeDriver(); driver.manage().window().maximize(); } @Test public void testGoogleSearch() { driver.get("https://www.google.com"); WebElement searchBox = driver.findElement(By.name("q")); searchBox.sendKeys("Selenium WebDriver"); searchBox.submit(); // Wait and verify title try { Thread.sleep(2000); } catch (InterruptedException e) {} String title = driver.getTitle(); Assert.assertTrue(title.contains("Selenium WebDriver"), "Title does not contain expected text!"); } @AfterClass public void tearDown() { if (driver != null) { driver.quit(); } } }
- Right-click on the test file → Run As → TestNG Test
- Or create a testng.xml:
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" > <suite name="MyTestSuite"> <test name="GoogleTest"> <classes> <class name="GoogleSearchTest" /> </classes> </test> </suite>
TestNG Annotations Summary
| Annotation | Description |
|---|---|
| @Test | Marks a test method |
| @BeforeClass | Runs once before any method in the class |
| @AfterClass | Runs once after all methods in the class |
| @BeforeMethod | Runs before each test method |
| @AfterMethod | Runs after each test method |