Practical 18: Setting up the TestNG Testing Framework
Aim
Set up TestNG (Test Next Generation) in Eclipse. Write several tests for the sample website. Use @Test, @BeforeMethod and @AfterMethod to organise the tests and their setup and cleanup. Run the test suite and read its report.
Theory
TestNG is a Java testing framework. It runs test methods and reports which passed, failed or were skipped.
Annotations are labels such as @Test above a method. They tell TestNG what the method does and when to run it. A test suite is a set of tests run together.
@BeforeClass = open the ground once in the morning. @BeforeMethod = reset the track before every race. @Test = each race. priority = the order of races. groups = "junior events" or "senior events" so you can run only one group. dependsOnMethods = the final runs only if the semi-final happened. testng.xml = the day's programme sheet.
Why TestNG over JUnit 4?
| Feature | TestNG |
|---|---|
| Rich annotations | Suite/test/group/class/method level setup and teardown |
| Priorities | @Test(priority = 1) controls order |
| Groups | @Test(groups = {"smoke"}) – run subsets |
| Dependencies | dependsOnMethods – skip dependent tests if a something needed before starting fails |
| Data-driven testing | @DataProvider supplies multiple data sets |
| Parallel execution | parallel="methods" in testng.xml |
| XML (Extensible Markup Language) suite configuration | testng.xml defines what runs |
| Built-in reports | HTML (Hypertext Markup Language) report (test-output/index.html, emailable-report.html) |
| Parameters | @Parameters from testng.xml (for example browser name) |
Annotation execution order
flowchart TB
BS[@BeforeSuite] --> BT[@BeforeTest] --> BC[@BeforeClass] --> BM1[@BeforeMethod] --> T1[@Test 1] --> AM1[@AfterMethod]
AM1 --> BM2[@BeforeMethod] --> T2[@Test 2] --> AM2[@AfterMethod]
AM2 --> AC[@AfterClass] --> AT[@AfterTest] --> AS[@AfterSuite]
| Annotation | Runs |
|---|---|
@BeforeSuite / @AfterSuite |
Once per suite |
@BeforeTest / @AfterTest |
Once per <test> tag in testng.xml |
@BeforeClass / @AfterClass |
Once per class – for example launch / quit the browser |
@BeforeMethod / @AfterMethod |
Before / after each @Test – for example open the home page, take screenshot on failure |
@Test |
A test method (attributes: priority, groups, dependsOnMethods, enabled, expectedExceptions, timeOut, dataProvider, description) |
@DataProvider |
Method returning Object[][] test data |
@Parameters |
Values injected from testng.xml |
TestNG assertions: Assert.assertEquals(actual, expected) (note: actual first), assertTrue, assertFalse, assertNotNull; soft assertions with SoftAssert collect failures and report them at assertAll().
Requirements
The .test addresses refer to the simulated practice app. Outside the simulator, use a running test app and its actual addresses and page elements.
- Eclipse, JDK (Java Development Kit) 17, Selenium Java 4.x, Chrome.
- TestNG – Eclipse plugin (Help → Eclipse Marketplace → TestNG for Eclipse) and
testng-7.x.jar(+jcommander), or Maven dependency. - AUT (Application Under Test): VLP Demo Store – home page, login, search, cart.
Procedure
Part A – Set up TestNG
- Help → Eclipse Marketplace… → search TestNG → Install → restart Eclipse.
- Create project
TestNGWebTests; Build Path → Add Library → TestNG; add Selenium JARs (Java Archives). Maven:
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.10.2</version>
<scope>test</scope>
</dependency>
Part B – Test class with multiple test methods
package vlp.testng;
import java.time.Duration;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.*;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.*;
public class DemoStoreTest {
private WebDriver driver;
private WebDriverWait wait;
private static final String BASE = "https://demo.virtuallp.test/";
@BeforeClass
public void launchBrowser() {
System.out.println("@BeforeClass – launching Chrome");
driver = new ChromeDriver();
driver.manage().window().maximize();
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@BeforeMethod
public void openHomePage() {
System.out.println("@BeforeMethod – opening home page");
driver.get(BASE);
}
@Test(priority = 1, groups = "smoke", description = "Home page title is correct")
public void verifyHomePageTitle() {
Assert.assertEquals(driver.getTitle(), "VLP Demo Store – Home");
}
@Test(priority = 2, groups = "smoke", description = "Logo and navigation are displayed")
public void verifyLogoAndMenu() {
Assert.assertTrue(driver.findElement(By.cssSelector("header .logo")).isDisplayed());
Assert.assertEquals(driver.findElements(By.cssSelector("nav a")).size(), 5);
}
@Test(priority = 3, groups = "regression", description = "Valid login reaches the dashboard")
public void validLogin() {
login("student", "Pass@123");
wait.until(ExpectedConditions.urlContains("/dashboard"));
Assert.assertEquals(driver.findElement(By.cssSelector(".user-name")).getText(), "student");
}
@Test(priority = 4, groups = "regression", dependsOnMethods = "validLogin",
description = "Logged-in user can add a product to the cart")
public void addToCart() {
login("student", "Pass@123");
driver.findElement(By.id("search")).sendKeys("headphones" + Keys.ENTER);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(".product-card .add"))).click();
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.id("cart-count"), "1"));
Assert.assertEquals(driver.findElement(By.id("cart-count")).getText(), "1");
}
@Test(priority = 5, dataProvider = "invalidLogins", groups = "regression",
description = "Invalid credentials are rejected")
public void invalidLogin(String user, String pass, String expectedError) {
login(user, pass);
String msg = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".alert-error"))).getText();
Assert.assertEquals(msg, expectedError);
}
@DataProvider(name = "invalidLogins")
public Object[][] invalidLogins() {
return new Object[][] {
{ "student", "wrong", "Invalid username or password" },
{ "nobody", "Pass@123", "Invalid username or password" },
{ "", "", "Username and password are required" },
};
}
@Test(enabled = false, description = "Payment gateway – not available in test environment")
public void payOnline() { }
@AfterMethod
public void afterEachTest(ITestResult result) {
System.out.println("@AfterMethod – " + result.getName() + " : "
+ (result.isSuccess() ? "PASSED" : "FAILED"));
driver.manage().deleteAllCookies(); // log out between tests
}
@AfterClass
public void closeBrowser() {
System.out.println("@AfterClass – quitting browser");
if (driver != null) driver.quit();
}
private void login(String user, String pass) {
driver.get(BASE + "login");
driver.findElement(By.id("username")).sendKeys(user);
driver.findElement(By.id("password")).sendKeys(pass);
driver.findElement(By.cssSelector("button[type=submit]")).click();
}
}
Part C – testng.xml suite
Right-click the class → TestNG → Convert to TestNG, then edit:
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="VLP Demo Store Suite" verbose="1">
<test name="Smoke and Regression">
<groups>
<run>
<include name="smoke"/>
<include name="regression"/>
</run>
</groups>
<classes>
<class name="vlp.testng.DemoStoreTest"/>
</classes>
</test>
</suite>
Part D – Run and analyse
- Right-click
testng.xml→ Run As → TestNG Suite. - Inspect the Results of running suite tab (passed/failed/skipped per method) and the console output.
- Open
test-output/index.htmlandemailable-report.htmlin a browser for the HTML report. - Make
validLoginfail (wrong expected name) and re-run:addToCartis skipped because it depends onvalidLogin.
Virtual lab · Testing Tools · 35 min
Organise web tests with TestNG and testng.xml
Run a TestNG class with priorities, groups, a data provider and a dependency, convert it to a testng.xml suite, filter by groups and watch a dependent test get skipped.
Output
Example output for the settings in this lesson:
@BeforeClass – launching Chrome
@BeforeMethod – opening home page
@AfterMethod – verifyHomePageTitle : PASSED
@BeforeMethod – opening home page
@AfterMethod – verifyLogoAndMenu : PASSED
@BeforeMethod – opening home page
@AfterMethod – validLogin : PASSED
@BeforeMethod – opening home page
@AfterMethod – addToCart : PASSED
@BeforeMethod – opening home page
@AfterMethod – invalidLogin : PASSED
@BeforeMethod – opening home page
@AfterMethod – invalidLogin : PASSED
@BeforeMethod – opening home page
@AfterMethod – invalidLogin : PASSED
@AfterClass – quitting browser
===============================================
VLP Demo Store Suite
Total tests run: 7, Passes: 7, Failures: 0, Skips: 0
===============================================
(The data-driven test runs three times; payOnline is disabled and not counted.)
Conclusion
Run the suite from testng.xml. Check that setup and cleanup run at the right times. Read the passed, failed and skipped results, and explain how groups, dependencies and test data affect the run.
Viva questions
- What is TestNG? List its advantages over JUnit 4. A Java test framework; it adds groups, priorities, dependencies, data providers, parallel runs, XML suites and HTML reports.
- Write the execution order of TestNG annotations.
@BeforeSuite→@BeforeTest→@BeforeClass→ (@BeforeMethod→@Test→@AfterMethod) × n →@AfterClass→@AfterTest→@AfterSuite. - Differentiate
@BeforeMethodand@BeforeClass.@BeforeMethodruns before every test method;@BeforeClassruns once before the first test in the class. - What is
testng.xml? What can it set up? The suite file – which classes, methods and groups to run, parameters, parallel mode and listeners. - What are groups and how are they included/excluded? Labels on tests (
groups = "smoke");<include>/<exclude>inside<groups><run>intestng.xml. - What happens to a test whose
dependsOnMethodstest fails? It is skipped, not failed. - Explain
@DataProviderwith an example. A method that returnsObject[][]rows of data; a@Test(dataProvider = "logins")runs once per row – for example three invalid logins in this practical. - Differentiate hard and soft assertions. A hard
Assertstops the test at the first failure;SoftAssertcollects failures and reports them all atassertAll().
Practise this topic
Hands-on virtual lab
Apply what you just read in a realistic, guided simulation. Free with a verified account.
Create a free account to track your progress and unlock virtual labs.