October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
automation testing

How to Use TestNG with Selenium in Java

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

To use TestNG with Selenium in Java, add both libraries to your build, create a TestNG class with @Test methods, start and quit a WebDriver in lifecycle methods, and use explicit waits before interacting with changing pages. The example below uses Maven, a Chrome browser, and a simple page assertion; it also shows how to run the test with Maven Surefire.

What TestNG and Selenium each do

Selenium WebDriver drives a real browser: it opens pages, finds elements, and performs browser actions. TestNG organizes and runs Java tests, provides setup and cleanup hooks, and reports outcomes. They work together, but they solve different parts of the job: Selenium controls the browser, while TestNG controls the test lifecycle and selection.

A useful starting pattern is one WebDriver per test method, created in @BeforeMethod and closed in @AfterMethod. Keep the driver isolated when adding parallel execution; browser sessions hold mutable state and should not be shared between concurrent tests.

Add the dependencies and choose versions

Use a build tool rather than adding JAR files manually. Pin the versions in your project and check the current Selenium release guidance and compatibility for your JDK and browser setup before choosing them. The TestNG project documentation gives org.testng:testng:7.9.0 as an example for JDK 11 users and 7.5.1 for JDK 8 users; those are examples, not a universal current-version matrix.

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

Maven

Add Selenium Java and TestNG to the project. Since the appropriate Selenium version depends on the project’s requirements, define selenium.version in your parent POM or build configuration as the specific release you have selected and pinned.

<properties>
  <maven.compiler.release>11</maven.compiler.release>
  <selenium.version>${selenium.version}</selenium.version>
  <testng.version>7.9.0</testng.version>
</properties>

<dependencies>
  <dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>${selenium.version}</version>
  </dependency>
  <dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>${testng.version}</version>
    <scope>test</scope>
  </dependency>
</dependencies>

Set selenium.version to the release you selected in your project’s version management; the property above makes that choice explicit rather than suggesting that one Selenium release is right for every environment. The TestNG version shown is the documented JDK 11 example. If your project targets JDK 8, use versions appropriate to that runtime rather than copying the JDK 11 example.

Gradle

Gradle uses the same artifacts, with dependency notation instead of XML. Pin the Selenium version you selected and use the TestNG example version appropriate to your JDK.

dependencies {
    testImplementation("org.seleniumhq.selenium:selenium-java:$seleniumVersion")
    testImplementation("org.testng:testng:7.9.0")
}

tasks.test {
    useTestNG()
}

Define seleniumVersion in the project’s Gradle configuration or version catalog. Maven and Gradle can both run TestNG; follow the build convention already used by your team.

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.

Write a first Selenium test with TestNG

This test opens the public example page at https://example.com/, waits for its heading to appear, and checks the heading text. It is a compile-ready test class once the dependencies above and a working Chrome browser/driver setup are in place. Replace the page and assertions with the behavior your application actually promises.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.time.Duration;

public class ExamplePageTest {
    private WebDriver driver;
    private WebDriverWait wait;

    @BeforeMethod
    public void setUp() {
        driver = new ChromeDriver();
        wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    }

    @Test
    public void examplePageShowsExpectedHeading() {
        driver.get("https://example.com/");

        String heading = wait.until(
            ExpectedConditions.visibilityOfElementLocated(By.cssSelector("h1"))
        ).getText();

        Assert.assertEquals(heading, "Example Domain");
    }

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

Name the file ExamplePageTest.java and place it in the test source directory, conventionally src/test/java. A TestNG test class is a Java class with at least one TestNG annotation. @Test may annotate a method or, in supported patterns, a class. The alwaysRun cleanup setting is useful so teardown is attempted even when setup or a test fails; the null check avoids calling quit() if driver creation did not complete.

new ChromeDriver() requires a usable Chrome browser and compatible driver setup for the Selenium version and machine. Configure that in your development or CI environment; do not assume a browser is installed on a headless build agent.

Use waits instead of timing guesses

A completed navigation does not guarantee that a JavaScript-driven page has finished changing. Selenium’s page-load wait concerns the document’s load state; scripts may still update the DOM afterward. An explicit wait polls until a stated condition becomes true, then returns the matching result or times out. Selenium describes explicit waits as loops that poll the application for a specific condition before continuing.

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

Prefer condition-based explicit waits

The example uses WebDriverWait with Duration.ofSeconds(10) and waits for a visible heading. Choose a condition that represents readiness for the next action: visibility before reading text, clickability before clicking, or presence when visibility is not required. A timeout is valuable information: the expected state did not arrive within the chosen limit.

Understand the alternatives

Wait style When it fits Trade-off
Explicit Wait for a particular element or state at the point it matters. Clear, local synchronization; requires choosing a meaningful condition.
Implicit A broad default wait for element lookup throughout the driver session. Less local control and can make failures harder to diagnose when combined with explicit waits.
Fluent An explicit wait where polling behavior and ignored exception types need finer control. More configuration; use it when the default explicit-wait behavior is insufficient.

The Java WebDriverWait(WebDriver, Duration) API ignores NotFoundException by default while evaluating its condition. Avoid fixed sleeps as normal synchronization: they either waste time when the page is ready early or still fail when it takes longer than the guessed delay. Also avoid mixing implicit and explicit waits without understanding the resulting timing behavior.

Run tests with Maven Surefire

Maven Surefire runs tests in Maven’s test phase. Conventionally named classes such as *Test.java are discovered automatically, so the example can be run from the project root with:

mvn test

The TestNG version and Surefire configuration documented in the sources are versioned examples, not requirements that every project use identical versions. The Apache Maven Surefire documentation example references Surefire 3.6.0 for JUnit Platform/TestNG integration. Check the Surefire documentation for the current configuration that matches your Maven and TestNG setup, especially when adding suite XML or advanced execution options.

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

Select suites and subsets as the project grows

Annotation-based discovery is enough for a small suite. Add a testng.xml suite file when you need to choose classes or groups explicitly, pass parameters, or control suite organization. TestNG groups let you mark related tests and select subsets; Maven Surefire documents configuration properties for groups and parameters. Keep the suite file and build configuration aligned so a command run locally selects the same intended tests as CI.

Use TestNG features without making tests brittle

  • Lifecycle hooks: @BeforeSuite/@AfterSuite cover a suite-wide fixture; @BeforeTest/@AfterTest cover a TestNG XML test; @BeforeGroups/@AfterGroups bracket groups; and @BeforeMethod/@AfterMethod run around each test method. Use the narrowest scope that matches the resource. A browser session used by one test normally belongs at method scope.
  • Groups: label tests such as smoke or regression and select the relevant group for a run. Groups organize selection, not test dependencies; keep each test understandable and independently diagnosable.
  • Parameters: pass environment or suite values through TestNG configuration instead of hard-coding them into test logic. Avoid putting secrets in source-controlled suite files.
  • Data providers: run the same test logic across multiple input sets. Keep each input case identifiable in reports so a failing data row can be traced to its values.
  • Expected exceptions and invocation controls: TestNG’s @Test supports expected exceptions, invocation counts, enabled flags, dependencies, and other test metadata. Use dependencies sparingly; a test that only works after an unrelated test can be difficult to rerun and debug.
  • Listeners and reporters: add these when you need custom reporting or integrations. They should improve failure diagnostics, not hide exceptions or turn failed assertions into apparent passes.

Parallel execution, performance, and reliable cleanup

Parallel execution can reduce suite wall time, but it is safe only when browser state is isolated. Do not share one mutable WebDriver across tests running at once. Give each concurrent test its own driver lifecycle and ensure test data, accounts, downloads, and application state do not collide. First make sequential tests repeatable; then enable parallelism in the suite configuration and validate that reports still identify each failure clearly.

For reliability, make setup and cleanup symmetrical, keep each test focused on an observable outcome, and avoid dependence on execution order. In CI, account for the actual browser environment and capture enough failure information—such as the failing test and relevant browser state—to diagnose issues. More workers also require more browser resources, so tune concurrency to the capacity of the machine rather than assuming that maximum parallelism is automatically faster.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot common failures

  • TestNG reports no tests: check that the class has a TestNG annotation, is under the test source directory, follows the build tool’s discovery naming conventions, and is included by any configured suite XML or group filter.
  • ChromeDriver cannot start: confirm Chrome is available in the execution environment and the Selenium/browser/driver setup is compatible. Check the CI image as well as your workstation; they may differ.
  • Element not found or wait timed out: verify the locator against the current page, confirm the test navigated to the expected URL, and wait for the right state rather than assuming the DOM is ready immediately after navigation.
  • Test passes locally but fails intermittently: look for fixed sleeps, shared browser or application state, execution-order assumptions, and tests competing for the same account or data. Replace guessed delays with explicit conditions and isolate resources.
  • Browser processes remain after failure: ensure teardown is annotated and runs even after a failed test, and call driver.quit() rather than closing only the current tab.
  • Maven does not launch TestNG: inspect the Surefire version and provider/configuration for the project’s TestNG setup, confirm dependency scope and suite settings, and check whether the selected tests match Surefire’s discovery rules.

Or skip the browser setup

If your need is to capture a page image or PDF—not to exercise interactive behavior such as login, clicks, or assertions against application state—ScreenshotNeo can take a screenshot with one GET request. It is a website screenshot API and MCP server, not a replacement for Selenium’s browser-driven functional tests. For visual evidence or page captures, its clean-shot behavior removes cookie banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, failed loads, and cache hits are not billed, with the response identifying the page verdict and billing status. AI agents can also use its MCP server tools, including take_screenshot, get_page_info, and capture_pdf.

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

Example cURL request, with the target URL adapted to the page you want:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com/ -o shot.webp

See the ScreenshotNeo API documentation for authentication and request options. Clean captures, selectable browser settings, CSS and JavaScript, waits, bulk capture, and other options are available; individual steps such as consent handling can be turned off. The free plan includes 1,000 screenshots per month without a card, and paid plans start at $5 for 3,000 screenshots. Visit ScreenshotNeo for the service details, or sign up free to try 1,000 screenshots a month with no card.

Frequently asked questions

Can I use TestNG without Maven?

Yes. TestNG and Selenium can be managed with Gradle or another Java build setup; Maven is used here because Surefire provides a common Maven test-running path.

Should I use Selenium screenshots instead of a screenshot service for every test?

No. Use Selenium when the test must drive a browser and verify application behavior. A screenshot API is suited to capturing a page image or PDF without writing and maintaining browser automation for that capture.

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

Frequently Asked Questions

Can I use TestNG without Maven?

Yes. TestNG and Selenium can be managed with Gradle or another Java build setup; Maven is used here because Surefire provides a common Maven test-running path.

Should I use Selenium screenshots instead of a screenshot service for every test?

No. Use Selenium when the test must drive a browser and verify application behavior. A screenshot API is suited to capturing a page image or PDF without writing and maintaining browser automation for that capture.

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.

Leave a Reply

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

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

Read next

Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.