October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

How to Use TestNG with Selenium in a Java Maven Project

A practical guide to combining Selenium WebDriver and TestNG in Java: Maven dependencies, browser lifecycle, suite execution, parallelization, and troubleshooting.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Selenium WebDriver to control the browser and TestNG to define, organize, and run the Java tests. In a Maven project, add both libraries as test dependencies, create a TestNG test with browser setup and cleanup, then run it through Maven Surefire or a TestNG suite XML file.

What TestNG and Selenium each do

Selenium WebDriver is the browser-automation API: your Java code asks it to navigate, find elements, and interact with a browser. A browser-specific driver mediates between Selenium and the browser. TestNG is the test framework around that automation. It provides test annotations, lifecycle hooks, grouping, suite configuration, and execution; it does not replace WebDriver.

A Java setup therefore needs the Selenium Java binding, TestNG, a browser, and the corresponding browser driver. Selenium’s getting-started guidance explains the browser and driver relationship, while its Java installation guide shows adding the binding with a build tool.

Add Selenium and TestNG to a Maven project

Declare both dependencies with test scope in pom.xml. Choose versions compatible with the project’s Java version and each other; the official TestNG Maven examples can be tied to particular JDK versions, so check current release documentation rather than copying an old sample version.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<dependencies>
  <dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>YOUR_SELENIUM_VERSION</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>YOUR_TESTNG_VERSION</version>
    <scope>test</scope>
  </dependency>
</dependencies>

Replace the version markers with actual versions before building; they are explanatory placeholders, not valid Maven versions. TestNG’s Maven guide covers dependency integration. Keep test classes under Maven’s conventional src/test/java source directory.

Write a browser test with setup and cleanup

TestNG treats a Java method annotated with @Test as a test method, as described in its documentation. The following example uses a public page and asserts its title. It assumes a compatible Chrome installation and driver are available to Selenium; driver provisioning can vary by Selenium and browser version, so verify the setup for your environment.

package example;

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 ExamplePageTest {
    private WebDriver driver;

    @BeforeMethod
    public void startBrowser() {
        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();
        }
    }
}

@BeforeMethod creates a browser session before each test method; @AfterMethod closes it after each method, including when a test fails. This favors isolation because cookies and page state do not carry over, but it has browser-startup cost. A wider lifecycle scope can reduce repeated startup when sharing is intentional, at the cost of greater risk that tests affect one another. Always quit sessions you create so browser processes are not left running.

Run tests through Maven or a TestNG suite

Run with Maven Surefire

Maven Surefire can discover and execute TestNG tests using conventional class naming and locations. Run the project’s test phase with:

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

For discovery details and configuration options, see the Maven Surefire TestNG guide.

Select classes, groups, or methods in testng.xml

As the suite grows, use testng.xml to explicitly select test classes, groups, or methods. For example, a minimal suite selecting one class is:

<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >
<suite name="Browser suite">
  <test name="Example tests">
    <classes>
      <class name="example.ExamplePageTest"/>
    </classes>
  </test>
</suite>

TestNG documents suite XML, command-line execution, groups, and selection rules in its documentation. Use a suite file when the selection and grouping need to be explicit; Maven’s ordinary test discovery is simpler for a small project.

Choose lifecycle scope and parallel execution deliberately

TestNG can run methods, classes, <test> blocks, or instances in parallel. The appropriate unit is whichever gives each concurrent test independent browser state and non-conflicting data.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Parallel unit Use when Check before enabling
Methods Methods can execute independently, including methods within a class. Do not share a mutable WebDriver or test data between concurrently running methods.
Classes Different test classes can run independently. Check shared fixtures, static state, and external test data for collisions.
<test> blocks Separate suite blocks represent independent work. Ensure resources and accounts used by the blocks do not overlap unsafely.
Instances Distinct test-class instances can safely operate at the same time. Ensure each instance owns its session and mutable state.

TestNG suite configuration can set the parallel mode and thread count. Add parallelism only after browser sessions and test data are isolated, and ensure the classes and shared state are thread-safe. More threads are not automatically faster if the browser host or application under test becomes the bottleneck.

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

Troubleshoot common setup failures

  • Maven cannot resolve a dependency: confirm the artifact coordinates and replace the version markers with real releases compatible with your Java version; then retry Maven after checking repository access.
  • Tests are not discovered: place tests under src/test/java, confirm they have TestNG @Test annotations, and check class naming or the selected classes in testng.xml. Surefire’s TestNG guide explains its discovery behavior.
  • Browser does not start: verify the browser is installed and that Selenium can obtain or locate a compatible driver for it. Browser and driver compatibility is environment-specific; consult Selenium’s installation material rather than assuming one setup works everywhere.
  • Test passes alone but fails in a suite: look for shared sessions, cookies, static fields, reused accounts, and conflicting data. Restore per-method isolation or make the shared resource safe for concurrency.
  • Browser processes remain after a failure: make cleanup unconditional with @AfterMethod(alwaysRun = true) and call quit() on the driver.
  • Parallel runs behave unpredictably: reduce concurrency or switch to a broader independent unit such as classes or suite blocks; do not parallelize methods that mutate shared state.

Or skip the browser setup

If the task is simply to capture a website image or PDF rather than interact with it as an automated test, ScreenshotNeo provides a one-request screenshot API and an MCP server for AI agents. For example, using cURL:

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 documentation for request options and response details. It removes cookie banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, and failed loads are not billed. Its MCP server lets AI agents take screenshots, and the free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up for 1,000 free screenshots a month, no card required.

Frequently Asked Questions

Can TestNG replace Selenium WebDriver?

No. TestNG structures and runs tests; Selenium WebDriver controls the browser.

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.

Do I need testng.xml for a small project?

No. Maven Surefire can run discovered TestNG tests; a suite file is useful when you need explicit class, group, or method selection.

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.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

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.