Selenium TestNG Integration

Selenium controls browsers but does not organize tests, generate reports, or manage execution order on its own. TestNG fills these gaps, adding structure and reporting around Selenium scripts.

Diagram: Where TestNG Fits

TestNG (organizes and runs tests)
      |
      v
Selenium WebDriver (controls the browser)
      |
      v
Actual Website

Installing TestNG

In Eclipse, install TestNG through the Eclipse Marketplace. In Maven projects, add the TestNG dependency inside the pom.xml file to pull the library automatically.

Basic TestNG Annotations

@Test

Marks a method as a test case that TestNG runs and reports on.

@Test
public void verifyPageTitle() {
    driver.get("https://www.estudy247.com");
    Assert.assertEquals(driver.getTitle(), "eStudy247 - Online Courses");
}

@BeforeMethod

Runs before every single @Test method, commonly used to open the browser fresh for each test.

@BeforeMethod
public void setUp() {
    driver = new ChromeDriver();
}

@AfterMethod

Runs after every single @Test method, commonly used to close the browser.

@AfterMethod
public void tearDown() {
    driver.quit();
}

@BeforeClass And @AfterClass

These run once before and once after all tests inside a class, useful for setup that does not need to repeat for every test method.

Assertions In TestNG

assertEquals()

Checks if two values match exactly, failing the test if they differ.

assertTrue() And assertFalse()

Checks if a condition evaluates to true or false.

Assert.assertTrue(driver.findElement(By.id("logo")).isDisplayed());

Grouping Tests

@Test(groups = "smoke")
public void verifyLoginPageLoads() {
    driver.get("https://www.estudy247.com/login");
    Assert.assertTrue(driver.findElement(By.id("email")).isDisplayed());
}

Groups let a team run only smoke tests before a release, skipping slower regression tests during quick checks.

Running Tests With testng.xml

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

This XML file defines which test classes run together as a suite, letting a build server trigger the entire group with one command.

Parallel Execution

<suite name="EstudySuite" parallel="tests" thread-count="3">

This setting runs multiple test classes at the same time using separate threads, cutting total execution time significantly on large test suites.

Practical Example

A QA team writes three TestNG classes for the course catalog: one for browsing, one for filtering, and one for checkout. TestNG opens a fresh browser before each test through @BeforeMethod, runs the group in parallel, and produces an HTML report showing pass and fail counts for every test method.

Leave a Comment

Your email address will not be published. Required fields are marked *