TestNG Complete Tutorial

TestNG is a powerful testing framework used in Selenium Automation Frameworks for managing execution, parallel runs, dependencies, reporting, and CI/CD integration.

← Back to Training

1. What is TestNG?

TestNG (Testing Next Generation) is an advanced testing framework inspired by JUnit and NUnit, designed to overcome limitations of traditional frameworks.

2. Installing TestNG

Maven Dependency

<dependency>
 <groupId>org.testng</groupId>
 <artifactId>testng</artifactId>
 <version>7.10.2</version>
 <scope>test</scope>
</dependency>

IDE Setup

3. First TestNG Program

import org.testng.annotations.Test;

public class FirstTest {

 @Test
 public void loginTest() {
   System.out.println("Login Successful");
 }
}

@Test annotation marks a method as a TestNG test case.

4. TestNG Annotations & Execution Flow

@BeforeMethod
public void setup(){
 System.out.println("Browser Launch");
}

@Test
public void testCase(){
 System.out.println("Test Executed");
}

@AfterMethod
public void tearDown(){
 System.out.println("Browser Closed");
}

5. Assertions in TestNG

Assert.assertEquals(actual, expected);
Assert.assertTrue(condition);
Assert.assertFalse(condition);
Assert.assertNull(object);
Assert.assertNotNull(object);

6. Priority, DependsOn, InvocationCount

@Test(priority=1)
public void launch(){}

@Test(priority=2, dependsOnMethods="launch")
public void login(){}

@Test(invocationCount=3)
public void repeat(){}

7. Groups

@Test(groups="smoke")
public void smokeTest(){}

@Test(groups="regression")
public void regressionTest(){}

8. DataProvider (Data-Driven Testing)

@DataProvider
public Object[][] loginData(){
 return new Object[][]{
  {"admin","admin123"},
  {"user","user123"}
 };
}

@Test(dataProvider="loginData")
public void login(String u,String p){}

9. testng.xml

<suite name="Suite">
 <test name="LoginTest">
  <classes>
   <class name="tests.LoginTest"/>
  </classes>
 </test>
</suite>

10. Parallel Execution

<suite parallel="methods" thread-count="3">

11. Listeners

public class Listener implements ITestListener{
 public void onTestFailure(ITestResult r){
  System.out.println("Failed:"+r.getName());
 }
}

12. Retry Failed Tests

public class Retry implements IRetryAnalyzer{
 int count=0;
 public boolean retry(ITestResult r){
  return count++ < 2;
 }
}

13. TestNG with Selenium

@BeforeClass
public void setup(){
 driver=new ChromeDriver();
}

@Test
public void openSite(){
 driver.get("https://google.com");
}

14. Interview & Real-Time Usage