ScreenshotNeo

BlogHow-to

How to Write Your First TestNG Automation Script

Build a small Java test with TestNG and Maven, then extend it to browser automation with Selenium WebDriver if your test needs a browser.

By the ScreenshotNeo team4 October 20267 min read

Start with a Java method annotated with TestNG’s @Test, then use an assertion to check its result. A browser is not needed for a framework smoke test. If by “automation script” you mean controlling a website, add Selenium WebDriver as a separate step: it starts a browser, interacts with a page, checks the result, and closes the session. TestNG supports unit through integration testing. TestNG documentation.

1. Create a minimal TestNG test

This first test checks Java behavior. The @Test annotation marks the method for TestNG, and the assertion makes the expected result a pass/fail condition.

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

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

If the assertion succeeds, the test passes. If it fails, TestNG reports the method as failed and includes the mismatch in the runner output. A test can also fail because its code throws an unexpected exception.

2. Add TestNG to a Maven project

Use Maven’s conventional test source directory, src/test/java. Add TestNG as a test-scoped dependency in pom.xml:

<dependencies>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>REPLACE_WITH_COMPATIBLE_VERSION</version>
        <scope>test</scope>
    </dependency>
</dependencies>

Choose a TestNG release compatible with your JDK and test runner. TestNG’s setup documentation shows different examples for different JDK versions, and its download page may show a different release than older examples. Check the current official Maven setup and download guidance rather than assuming a version number in a tutorial is universally suitable. Maven Surefire’s TestNG integration guide documents dependency setup and test discovery.

Save the example as src/test/java/FirstTest.java. If the project does not already configure Maven Surefire, Maven’s standard test lifecycle normally runs tests through that plugin; use the plugin’s current documentation if your project has a custom build or runner setup.

3. Run it and read the result

  1. From the project directory, run mvn test.
  2. Wait for Maven to resolve the test dependency and execute the test phase.
  3. Check the summary and test report output. A discovered, passing test should be reported as successful; a failed assertion or exception should identify the failing method.

You can also run a TestNG class from an IDE that supports TestNG. IntelliJ IDEA documents creating and running TestNG tests in its TestNG guide. IDE execution is convenient while editing; Maven execution is useful for repeatable command-line runs and build automation.

4. Add useful checks and organize tests

Replace the arithmetic expression with behavior from your application. A good test makes the input, action, and expected result visible. Keep each test focused enough that a failure points toward one behavior.

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

public class PriceCalculatorTest {
    @Test
    public void appliesNoDiscountToSmallOrder() {
        PriceCalculator calculator = new PriceCalculator();

        int total = calculator.totalFor(2, 10);

        Assert.assertEquals(total, 20);
    }
}

This example assumes your project has a PriceCalculator class with a matching method; it is a pattern, not a complete application. TestNG assertions compare actual results with expectations. When a check is false, the assertion fails the test. For setup and cleanup shared by several tests, TestNG provides lifecycle annotations; see its official documentation for annotation ordering and configuration options.

5. Optional extension: automate a browser with Selenium

A TestNG test does not itself open a browser. If the behavior under test lives in a website, use Selenium WebDriver alongside TestNG. The browser workflow is: create a driver session, navigate to a page, find controls, interact, assert the result, and quit the session.

Add Selenium’s Java library to Maven as well. Use the official Selenium Java library setup for a version compatible with your JDK and build configuration:

<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>REPLACE_WITH_COMPATIBLE_VERSION</version>
    <scope>test</scope>
</dependency>

Here is a TestNG-shaped adaptation of Selenium’s official web-form example. The finally block closes the session even if navigation, interaction, or an assertion fails.

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

public class WebFormTest {
    @Test
    public void submitsTheWebForm() {
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://www.selenium.dev/selenium/web/web-form.html");

            WebElement input = driver.findElement(By.name("my-text"));
            input.sendKeys("TestNG");
            driver.findElement(By.cssSelector("button")).click();

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

Selenium’s first-script guide covers the sample page and browser interaction pattern. Use the current guide for prerequisites and browser/driver setup details; those can vary by Selenium release and environment. In larger suites, consider putting driver setup and teardown in TestNG lifecycle methods so each test gets an appropriately managed browser session.

6. Troubleshooting

Symptom Likely cause What to check
Maven cannot resolve TestNG Invalid dependency coordinates, repository/network issue, or incompatible version selection. Confirm the group and artifact are org.testng:testng, check Maven’s error output, and choose a release compatible with the project JDK.
mvn test says there are no tests The file is outside the test source tree, the class/method is not discoverable by the configured runner, or Surefire/provider configuration differs. Place the class under src/test/java, confirm the method has @Test, and review the project’s Surefire version and naming/discovery rules.
Imports such as org.testng.Assert are unresolved TestNG has not been added to the project model or dependency refresh has not completed. Check the dependency in pom.xml, reload Maven in the IDE, and inspect Maven resolution errors.
The IDE runs the class differently from Maven The IDE may use a different JDK, classpath, or TestNG runner configuration. Align the selected JDK and dependency versions, then reproduce with mvn test and inspect the IDE run configuration.
Selenium cannot start Chrome Browser installation, driver management, permissions, or runtime environment is not configured as Selenium expects. Follow Selenium’s current Java setup guide for the installed browser and environment. Read the startup exception before changing versions.
Element lookup fails or times out The page structure changed, the locator is wrong, or the element is not ready when queried. Inspect the current page and locator; use an explicit wait for dynamic content rather than adding an arbitrary long sleep.
Browser stays open after a failed test Cleanup did not run on the failure path. Keep driver.quit() in a finally block or a teardown method that TestNG runs after the test.

7. Performance, reliability, and cost

A TestNG-only unit-style check avoids browser startup and is usually the lighter choice for testing a Java method. Browser tests add browser startup, page loading, and external page behavior, so keep them for behavior that actually requires a browser. Prefer stable locators and condition-based waits for pages that load asynchronously. Always close WebDriver sessions to avoid consuming local or CI resources.

TestNG and Selenium are software libraries; this workflow does not require a paid screenshot service or a particular IDE. Build cost depends on your chosen runtime and infrastructure. Pin mutually compatible dependency versions in the project and update them deliberately, rather than copying version numbers from an older snippet.

Or skip the browser setup

If your goal is a screenshot of a page rather than a browser interaction test, ScreenshotNeo is a website screenshot API and MCP server. One GET request returns a PNG, JPEG, WebP, or PDF. The examples below use the documented endpoint; see the ScreenshotNeo API documentation for request options.

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

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
  • Cookie banners are accepted like a visitor, and 60+ known consent platforms, newsletter popups, and chat widgets are removed before the shot; each step can be turned off.
  • Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing. Response headers identify the page verdict and billing status.
  • An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents and MCP clients.
  • The free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 screenshots; every feature is on every plan.

Create a free ScreenshotNeo account for 1,000 screenshots a month with no card.

FAQ

Does every TestNG automation script need Selenium?

No. TestNG can check Java behavior without launching a browser. Add Selenium only when the test needs to control a web browser.

Can TestNG run tests from an IDE?

Yes. IDEs with TestNG support can run test classes, and Maven can run them through the project’s test lifecycle.

What does an assertion do?

It compares an outcome with an expectation and marks the test failed when the check does not hold.

Where should a Maven test class go?

Use src/test/java for conventional Maven test sources, unless the project explicitly configures another location.