Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober 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 Now×
Skip to content
World desk5 min

How to Use TestNG Assertions in Selenium Tests

Use Selenium to observe a browser result, wait for the page to reach the right state, and then assert it with TestNG in Java.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Selenium to perform an action, wait until the browser shows the expected result, then use an assertion to compare that result with what the test requires. Selenium supplies the observed page state; TestNG runs the Java test and records an assertion failure as a failed test.

How TestNG assertions fit into a Selenium test

A browser action alone does not establish that a test passed. After clicking a button, submitting a form, or navigating to a page, check an observable outcome such as the page title, visible text, or an input value. Selenium identifies TestNG as one Java test-runner option; JUnit is another. TestNG also supports parallel execution and parameterized tests. Selenium: Organizing and Executing Selenium Code

In a typical test, Selenium drives the browser and reads the result, while an assertion compares that result with the expected value:

  1. Perform the browser action.
  2. Wait for the page state that indicates the action succeeded.
  3. Read the observed value.
  4. Assert that it matches the expectation.

Assert a page title or visible text

TestNG documentation demonstrates the JUnit Assert API for comparisons, including assertEquals with a static import. Here is a complete example using that API with Selenium and TestNG:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import static org.junit.Assert.assertEquals;

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.annotations.Test;

import java.time.Duration;

public class SearchTest {
    @Test
    public void submittingSearchShowsResults() {
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://example.com/search");
            driver.findElement(By.name("q")).sendKeys("selenium");
            driver.findElement(By.cssSelector("button[type='submit']")).click();

            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("results")));

            String actualText = driver.findElement(By.id("results")).getText();
            assertEquals("Expected search results to be shown", "Results for selenium", actualText);
        } finally {
            driver.quit();
        }
    }
}

Replace the example URL, selectors, and expected text with values from the application under test. The assertion’s message explains what the check was meant to establish; the expected and actual values make the comparison clear. The wait ensures the result is visible before its text is read.

What happens when an assertion fails

A TestNG test passes when it completes without an exception, or when it throws an exception the test declares as expected. A failed assertion throws AssertionError, so TestNG marks that test method as failed. TestNG’s documentation also shows Java’s language-level assert keyword, but that keyword only fires when the JVM is run with assertions enabled using -ea. If a Java assert appears to be ignored, check the JVM options. TestNG Documentation

Wait for the page before asserting

Navigation can return before page JavaScript has finished updating the page. Reading an element or title immediately after an action can therefore observe an old or incomplete state. Selenium describes this as a timing race and recommends waiting for the specific state the test needs rather than relying on a guessed pause. Selenium: Waiting Strategies

Use an explicit wait for the expected condition

WebDriverWait polls until a condition succeeds or its timeout expires. Selenium’s expected conditions include element presence, visibility, text visibility, and title content. Choose the condition that proves the outcome relevant to the test: for example, wait for result text to become visible before asserting its exact value, or wait for a title to contain the expected content before reading it.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

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

Do not mix implicit and explicit waits

Selenium’s implicit wait is a global setting for element-location calls and defaults to zero. Selenium warns that combining implicit and explicit waits can produce unpredictable timeout durations. Prefer a clear explicit wait for the state under test instead of setting an implicit wait as well.

Why a fixed sleep is a weak substitute

A fixed sleep pauses for the same duration whether the page is ready or not. A short pause may expire too early on a slower run; a long one wastes time when the page is ready sooner. Condition-specific waits stop when the relevant state appears, while still timing out if it never does.

Choose the assertion style that fits the check

Approach Useful for Failure and setup note
JUnit Assert API Comparing values such as expected and actual text, titles, or other objects. TestNG’s documentation demonstrates this API and a static import of assertEquals. A failed comparison throws an assertion error that fails the test.
Java assert keyword A language-level assertion when JVM assertions are enabled. Run the JVM with -ea; otherwise Java assertions may not fire.

The key choice is not a universal winner between assertion styles. Use a comparison that makes the expected outcome understandable, and make sure Selenium has observed the intended page state before checking it.

Common assertion failures and fixes

  • Text or title is still the previous value: the page may not have completed its asynchronous update. Wait for the expected text, element visibility, or title condition before reading and asserting.
  • An element lookup fails immediately after an action: wait for that element to be present or visible, depending on what the test needs to do with it.
  • The assertion reports expected and actual values that look reversed: inspect the assertion argument order and compare the expected value with the value Selenium actually read.
  • A Java assert does not fail when the condition is false: ensure the JVM is launched with -ea, or use the documented assertion API.
  • Wait durations seem longer or inconsistent: check whether implicit and explicit waits are both configured. Selenium cautions against mixing them.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If the goal is a clean image or PDF of a page rather than an automated browser assertion, ScreenshotNeo is a website screenshot API and MCP server. Its one-request API can return an image or PDF; it does not replace Selenium tests or TestNG assertions.

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

One-call cURL example (see the ScreenshotNeo documentation):

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
  • It accepts cookie or consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each of those steps can be turned off.
  • Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed. Responses include X-Page-Verdict and X-Billed headers.
  • An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.
  • The free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots.

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

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. 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
Outdated Drivers Are Slowing You DownFree scan - exact matches

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.