Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober 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 PC×
Skip to content
World desk6 min

How to Write Your First TestNG Automation Script

Start with a simple Java behavior test using TestNG and Maven, then add Selenium only if your automation needs to drive a browser.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Your first TestNG script can be a small Java test that checks a result and reports pass or fail—no browser required. If by “automation” you mean controlling a website, add Selenium WebDriver as a separate step; TestNG runs the test, while Selenium drives the browser.

What a TestNG test does

TestNG is a Java testing framework used for tests ranging from unit checks to integration tests. A test method uses annotations such as @Test to identify it for execution. Assertions state what should be true; if an assertion fails, the test fails. A plain TestNG test checks Java behavior and does not itself open or control a browser. See the TestNG documentation for its annotations, assertions, and execution model.

Set up a minimal Java and Maven project

Use Maven to provide TestNG as a test dependency, and put test classes in the conventional src/test/java directory. TestNG’s Maven setup page and Maven Surefire’s guide document dependency-based execution. Their examples and runner behavior depend on the JDK and plugin versions, so check the current compatibility guidance rather than copying a version number from an older example: TestNG Maven setup, TestNG downloads, and Maven Surefire TestNG guide.

Add TestNG to the project’s pom.xml with test scope. For example, the dependency has this shape; select a release compatible with your JDK and project rather than treating the version placeholder as a literal value:

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

The version must be replaced with a real compatible release before Maven can build the project. TestNG’s published setup information includes examples associated with different JDK baselines; the right choice is not universal.

Write and run your first TestNG test

Create src/test/java/FirstTest.java and add this minimal test:

import org.testng.Assert;
import org.testng.annotations.Test;

public class FirstTest {
    @Test
    public void additionReturnsExpectedSum() {
        int actual = 2 + 3;
        Assert.assertEquals(actual, 5);
    }
}

@Test marks the method for discovery. Assert.assertEquals(actual, 5) compares the computed value with the expected value: a match passes; a mismatch throws an assertion failure and marks the test failed. This is a teaching example, not a browser test.

  1. Save the file under src/test/java, not the production source folder.
  2. From the project directory, run mvn test. Maven Surefire uses the TestNG dependency and its test-discovery conventions to run tests.
  3. Read the Maven output and test report for the number of tests and their pass/fail status. A successful build means this test completed without a failure; it does not establish anything about a website or browser.

You can also run a TestNG class or method from an IDE. IntelliJ IDEA documents creating and running TestNG tests; exact menus can vary by release. See IntelliJ IDEA’s TestNG guide.

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

When the script needs to control a browser: add Selenium

If your goal is to visit a page, enter text, click a control, and check what appears, use Selenium WebDriver alongside TestNG. Selenium starts and controls a browser session; TestNG discovers and evaluates the test. The Selenium Java first-script walkthrough uses a web form at https://www.selenium.dev/selenium/web/web-form.html and demonstrates locating a text box and button, entering text, reading a result, and closing the session. Its Java setup describes JDK and Maven prerequisites.

Add Selenium’s Java library as a Maven dependency using the artifact org.seleniumhq.selenium:selenium-java. Follow the official page for a version compatible with your Java setup: Selenium Java library installation. Keep both TestNG and Selenium dependencies in test scope if they are only used by tests.

Here is a TestNG-shaped adaptation of Selenium’s first browser workflow. It checks the returned message and closes the browser even if an operation or assertion fails:

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

public class BrowserFormTest {
    @Test
    public void submitsWebForm() {
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://www.selenium.dev/selenium/web/web-form.html");
            driver.findElement(By.name("my-text")).sendKeys("TestNG");
            driver.findElement(By.cssSelector("button")).click();

            String message = driver.findElement(By.id("message")).getText();
            Assert.assertEquals(message, "Received!");
        } finally {
            driver.quit();
        }
    }
}

This example uses Selenium’s documented sample form and a TestNG assertion. Browser and driver availability must be configured for the environment where the test runs; consult Selenium’s current setup instructions for supported browsers and driver management. A teardown method annotated with TestNG’s @AfterMethod is another way to centralize cleanup when a class has multiple browser tests.

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

Browser tests add moving parts: a browser session, page load, selectors, and the page’s behavior. Keep assertions tied to a visible outcome, use stable selectors where possible, and make cleanup unconditional so a failed assertion does not leave the browser running.

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

Choose the right way to run it

Approach Best for What to check
IDE TestNG run action Running a class or method while editing TestNG is available to the project and the IDE recognizes the test source and annotation.
mvn test Repeatable project-level execution and build integration Maven resolves compatible dependencies and Surefire discovers the test class.
TestNG-only Java test Checking logic or a Java behavior without a browser The assertion expresses the intended expected result.
TestNG with Selenium Checking an actual browser interaction or rendered page result Browser setup, element locators, page readiness, and session cleanup.

Troubleshoot tests that will not run

  • TestNG imports are unresolved or Maven cannot resolve the dependency: confirm the dependency is in pom.xml, the version is real and compatible with the project’s JDK, and Maven can reach its configured repositories. Reimport or reload the Maven project in the IDE.
  • The file compiles but no tests are found: check that the class is under src/test/java, the method has @Test, and the class name follows the test naming patterns expected by your Surefire configuration. Review Surefire’s TestNG discovery guidance if you customized the plugin.
  • The IDE does not offer a TestNG run action: verify the TestNG dependency is recognized and that the class is treated as a test source. IDE menus differ by version; compare your setup with the current IntelliJ TestNG documentation.
  • mvn test runs zero tests or behaves differently from the IDE: inspect the Maven output and Surefire reports, then check the plugin version and discovery configuration. IDE execution and Maven execution use different runners and configuration paths.
  • The Java test passes but the browser test fails to start: check Selenium’s current browser and driver setup guidance, installed browser availability, and the runtime environment. The TestNG-only test does not require any of those browser components.
  • The browser opens but the interaction or assertion fails: confirm the page loaded, the locator still matches the intended element, and the expected text is the actual result. Use the failure output to distinguish an element lookup or timing problem from an incorrect assertion.

Or skip the browser setup

If what you need is a screenshot rather than an interactive Selenium test, ScreenshotNeo is a website screenshot API and MCP server. A single request can return an image or PDF without setting up a browser session in your project. For example, using cURL:

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

See the ScreenshotNeo API documentation for request options. Cookie banners, popups, and chat widgets are removed before the shot; bot checks, blank pages, and failed loads are never 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 with no card.

Frequently Asked Questions

Does TestNG require Selenium?

No. TestNG can run Java tests on its own; Selenium is an additional library for browser interaction.

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

What does a failed assertion mean?

The test’s actual value did not match the expected value, so TestNG reports the test as failed.

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 *

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.

More from the Wire

  1. 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…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
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.