TestNG-Tutorial
TestNG-Tutorial
Beginners to Advanced
Table of Contents
1. Introduction to TestNG
2. Core Concepts
3. Annotations
4. Test Configuration
5. Test Parameters
6. Groups and Dependencies
7. Parallel Testing
8. Test Reports
9. Real-world Examples
1. Introduction to TestNG
What is TestNG?
TestNG (Test Next Generation) is a testing framework inspired by JUnit and NUnit,
introducing innovative functionalities for making testing more powerful and easier.
Key Features
● Annotations
● Test dependencies
● Parallel execution
● Data-driven testing
● Flexible test configuration
2. Core Concepts
Basic Test Structure
import org.testng.annotations.Test;
import org.testng.Assert;
3. Annotations
Common Annotations
public class AnnotationsDemo {
@BeforeSuite
public void beforeSuite() {
// Executes before test suite
}
@BeforeTest
public void beforeTest() {
// Executes before test
}
@BeforeClass
public void beforeClass() {
// Executes before class
}
@BeforeMethod
public void beforeMethod() {
// Executes before each test method
}
@Test
public void testMethod() {
// Test case
}
@AfterMethod
public void afterMethod() {
// Executes after each test method
}
@AfterClass
public void afterClass() {
// Executes after class
}
@AfterTest
public void afterTest() {
// Executes after test
}
@AfterSuite
public void afterSuite() {
// Executes after test suite
}
}
4. Test Configuration
testng.xml
5. Test Parameters
Data Provider Example
XML Parameters
<suite name="Suite">
<parameter name="browser" value="chrome"/>
<test name="ParameterTest">
<classes>
<class name="ParameterizedTests"/>
</classes>
</test>
</suite>
public class XMLParameterTest {
@Parameters({"browser"})
@Test
public void testBrowser(String browser) {
System.out.println("Testing with browser: " + browser);
}
}
7. Parallel Testing
Parallel Execution Configuration
@Test(dataProvider = "loginData")
public void testLogin(String username, String password, boolean
expectedResult) {
driver.get("http://example.com/login");
driver.findElement(By.id("username")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
driver.findElement(By.id("loginButton")).click();
boolean actualResult =
driver.findElement(By.id("welcomeMessage")).isDisplayed();
Assert.assertEquals(actualResult, expectedResult);
}
@AfterClass
public void tearDown() {
driver.quit();
}
}
Practice Exercises
Parameterized Test: