Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Selenium WebDriver controls a browser; TestNG organizes and runs Java tests that use WebDriver. To build a maintainable Selenium with TestNG framework, create a Java project with both dependencies, write an annotated test with setup and cleanup, then use TestNG configuration—including an optional testng.xml suite—to select and run tests. Start with isolated, reliable local tests before introducing parallel execution or Selenium Grid.

What Selenium and TestNG each do

Selenium WebDriver is the browser-control API and protocol. Your Java code calls Selenium; a browser-specific driver mediates communication with the browser. A working local setup therefore needs Java, the Selenium Java binding, a browser, and a compatible driver. TestNG is the test-runner and organization layer: its annotations mark tests and lifecycle methods, while its runner and configuration define what executes and when. Selenium’s getting-started guide explains the browser-control components, and TestNG’s documentation describes the runner and suite configuration.

These tools are complementary, not alternatives. Selenium can be called from different test frameworks; this tutorial uses TestNG to arrange and execute Java browser tests. The usual TestNG hierarchy is suite, test, class, and annotated test method. A suite may be declared in XML or in build configuration.

Set up a Java project and dependencies

Choose a build tool and verify versions

Use Maven or Gradle to declare Selenium and TestNG so that dependency resolution and repeatable builds are handled by the project. The current Selenium Java artifact version, Java baseline, browser/driver support, and a joint Selenium–TestNG compatibility matrix are not established here. Check the projects’ official release and compatibility information before pinning versions; do not treat a version displayed on a project home page as proof that it is the latest.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For Maven, add the Selenium Java and TestNG artifacts to pom.xml, selecting versions verified for your Java runtime. Configure the Maven test runner to use TestNG if your project setup requires it. For Gradle, declare the same dependencies in the appropriate test configuration and use a TestNG test task. Keep versions explicit in the build so another developer or a CI job resolves the same libraries.

Prepare the browser

  1. Install a supported Java runtime and a browser on the machine that will execute the test.
  2. Add the Selenium Java binding and TestNG to the build.
  3. Confirm the browser and its driver can communicate. Selenium’s setup guide describes the required components; exact compatibility depends on your browser, driver, Selenium release, and environment.
  4. Create a test source file in your build tool’s test source directory and run it through TestNG.

Keep environment-specific browser setup outside the assertion itself. If you later move execution to a remote browser, you can replace local driver creation with remote configuration without changing the basic role TestNG plays.

A first Selenium TestNG test in Java

This example demonstrates the essential shape of a test: create a WebDriver, navigate, check an observable result, and quit the browser even if an assertion fails. Substitute a stable page you are authorized to test for the example URL if needed. The example uses Selenium’s Java APIs and TestNG annotations; confirm imports and dependency versions in your chosen project.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class HomePageTest {
    private WebDriver driver;

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

    @Test
    public void pageHasExpectedTitle() {
        driver.get("https://example.com");
        Assert.assertEquals(driver.getTitle(), "Example Domain");
    }

    @AfterMethod(alwaysRun = true)
    public void closeBrowser() {
        if (driver != null) {
            driver.quit();
        }
    }
}

TestNG discovers the method marked @Test. Before each test method, @BeforeMethod creates a browser session; after the method, @AfterMethod closes it. The alwaysRun setting makes cleanup run even when the test fails. The null check also avoids a cleanup error if browser creation itself did not complete.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a real application, assert a meaningful user-visible condition—such as a heading, URL, or success state—rather than merely checking that navigation returned. Keep locators and test data stable, and avoid depending on mutable state left by another test.

TestNG lifecycle annotations and scope

TestNG provides before/after configuration hooks at suite, test, group, class, and method scopes. Pick the narrowest scope that matches the resource being managed. A browser per method is a straightforward starting point because each test gets a fresh session; broader sharing can be faster in some designs but introduces state coupling and cleanup complexity.

  • @BeforeSuite / @AfterSuite: work around the whole suite, such as suite-wide preparation and final cleanup.
  • @BeforeTest / @AfterTest: work around a TestNG XML <test> section.
  • @BeforeClass / @AfterClass: work around methods in one class.
  • @BeforeMethod / @AfterMethod: work around each test method, useful for isolated browser sessions.
  • @BeforeGroups / @AfterGroups: work around methods belonging to a named group.

Use configuration annotations for setup and teardown rather than hiding essential preparation inside test methods. If a test fails, teardown should still release browser resources. Do not share one mutable WebDriver across unrelated tests by default: parallel execution or test ordering can otherwise make outcomes depend on hidden state.

How to create a testng.xml file in Selenium

A testng.xml file tells TestNG which classes, methods, or groups belong to a suite and can also configure execution. Here is a minimal suite selecting the class above:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<?xml version="1.0" encoding="UTF-8"?>
<suite name="Browser checks">
  <test name="Home page">
    <classes>
      <class name="HomePageTest"/>
    </classes>
  </test>
</suite>

Place the file where your chosen build or IDE configuration expects it, then invoke the TestNG runner with that suite file. If the class is in a package, use its fully qualified name in the class element. The XML’s <test> is a TestNG grouping construct; it is not the same thing as a Java method annotated with @Test.

As the suite grows, XML can select classes or groups without changing each test method. TestNG also documents configuring execution through build files, so XML is useful but not mandatory. See the TestNG documentation for the available suite and runner configuration.

Organize tests as the suite grows

Separate test intent from shared infrastructure. Keep test classes focused on related behaviors, group tests when a suite needs to select a subset, and keep configuration code responsible for browser lifecycle. A simple suite may contain one class; a larger one can separate smoke checks, feature coverage, and environment-specific runs through suite configuration or groups.

The goal is not to add abstraction for its own sake. Introduce shared helpers when they remove duplicated setup or make waits, navigation, and assertions consistent. Preserve clear test names and make failures point to the behavior that failed. Selenium’s material on organizing and executing Selenium code covers Java examples and test organization.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

When and how to run tests in parallel

Parallelism can run independent work concurrently, but it is not a guaranteed speed multiplier. TestNG documents parallel units including methods, tests, classes, and instances, along with a thread count. Choose the unit based on what can safely run independently, then size concurrency to available browser and machine capacity.

Parallel unit What runs concurrently Consider before enabling it
Methods Test methods Methods must not depend on execution order or shared mutable browser/data state.
Tests XML-level TestNG tests Check that each configured test can use separate resources and data.
Classes Test classes Class-level setup and shared fixtures must not collide.
Instances Test instances Instance state must remain isolated and the test data must support concurrent use.

Set the thread count deliberately rather than maximizing it by default. Each concurrent browser consumes resources, and an overloaded machine can make runs slower or less reliable. Ensure each parallel worker has an independent WebDriver session and safe test data; if a class is not thread-safe, keep its work together rather than letting concurrent methods mutate shared state. TestNG’s documentation describes parallel modes and thread-count configuration.

Run locally first so failures are easier to diagnose. When you need execution across machines or platforms, Selenium Grid provides distributed browser execution; it adds environment and network setup as well as capacity. Selenium’s overview describes Grid’s role. Treat remote execution as a scaling step after the tests are stable, not as a fix for flaky tests.

Troubleshooting common failures

  • Browser does not start: confirm Java, browser, Selenium binding, and browser driver are present and mutually compatible. Check the driver startup error for the failing component rather than changing several versions at once.
  • TestNG reports no tests: confirm the method has @Test, the class is selected by the runner or suite XML, the package name in XML is correct, and the build is configured to invoke TestNG.
  • Suite XML cannot find a class: use the class’s fully qualified name and ensure the class is on the test classpath.
  • Browser remains open after a failure: place quit() in an after-method or other appropriate teardown hook, and configure it to run after failures.
  • Tests pass alone but fail together: look for shared browser sessions, mutable fixtures, reused accounts or records, and order dependencies. Isolate sessions and data before increasing concurrency.
  • Parallel run is unstable or slower: lower the thread count, confirm resource capacity, check thread safety and independent test data, and compare against a reliable sequential run.
  • Local tests work but Grid tests fail: inspect remote browser availability, network reachability, and the remote session configuration; Grid introduces a separate execution environment.

Or skip the browser setup

If your task is to capture a page image rather than automate browser interactions and assertions, ScreenshotNeo provides a website screenshot API and MCP server. It removes cookie/consent banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, and failed loads are not billed. AI agents can use its MCP server to take screenshots. The free plan includes 1,000 screenshots per month with no card, and paid plans start at $5 for 3,000 screenshots. See ScreenshotNeo and its API documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp

Sign up free for 1,000 screenshots a month with no card.

Frequently Asked Questions

Can I use Selenium without TestNG?

Yes. Selenium WebDriver is a browser-control library; TestNG is one Java test runner that can organize and execute tests using it.

Does testng.xml replace the Java test class?

No. It selects and configures suite contents; the annotated Java test methods still contain the test behavior.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.