JUnit Assertions for Selenium Testing: Examples
Use JUnit Jupiter assertions to verify Selenium browser results, wait for dynamic content, and check expected exceptions with clear failure messages.
Use JUnit Jupiter assertions to check what Selenium reads from the browser after an interaction. Use assertEquals(expected, actual) for titles, visible text, attributes, and input values; use boolean assertions for conditions; and use assertThrows only when the test expects an operation to throw. If the page updates asynchronously, wait for the relevant condition before reading and asserting the result.
This guide uses Java, Selenium WebDriver, and JUnit Jupiter. The examples show assertion patterns, not a compatibility guarantee for any particular Java, Selenium, driver, or browser version. Check the current documentation for the versions used by your project.
1. Add assertions to a Selenium test
Import the JUnit assertion you need with a static import. Perform the browser action, read the resulting browser state, then compare it with the expected value. That makes the assertion verify an observable result rather than merely confirming that a method was called.
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
class FormTest {
@Test
void submittingFormShowsConfirmation() {
WebDriver driver = new ChromeDriver();
try {
driver.get("https://www.selenium.dev/selenium/web/web-form.html");
assertEquals("Web form", driver.getTitle(), "page title");
driver.findElement(By.name("my-text")).sendKeys("Ada");
driver.findElement(By.cssSelector("button")).click();
String message = driver.findElement(By.id("message")).getText();
assertEquals("Received!", message, "submission confirmation");
} finally {
driver.quit();
}
}
}
The page URL and expected values follow Selenium’s Java getting-started example. Use the test runner and dependency setup already established by your project. The Selenium documentation shows checking the title, submitting a form, and checking its confirmation message in its Java example.
Choose the assertion that matches the result
| What you need to check | Assertion pattern |
|---|---|
| Two values should match | assertEquals(expected, actual) |
| A condition should be true or false | assertTrue(condition) or assertFalse(condition) |
| A value should be null or non-null | assertNull(value) or assertNotNull(value) |
| A reference should be the same object | assertSame(expected, actual) |
| An operation should throw a particular exception | assertThrows(ExceptionType.class, executable) |
JUnit Jupiter provides these assertion methods in its Assertions API. Prefer the assertion whose name makes the intended condition clearest.
2. Assert page titles, text, attributes, and input values
Selenium exposes different ways to read browser state. Select the one that corresponds to the behavior the test is meant to protect.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
// Page title
assertEquals("Account", driver.getTitle(), "title after navigation");
// Visible text rendered inside an element
String status = driver.findElement(By.id("status")).getText();
assertEquals("Saved", status, "save status");
// DOM attribute, such as an accessible label
String label = driver.findElement(By.id("email")).getAttribute("aria-label");
assertEquals("Email address", label, "email field label");
// Current value of an input element
String value = driver.findElement(By.id("email")).getDomProperty("value");
assertEquals("ada@example.test", value, "email field value");
// Predicate check
assertTrue(driver.findElement(By.id("save")).isEnabled(), "save button should be enabled");
getText() checks the element’s rendered text. An input’s entered value is generally a DOM property, so use getDomProperty("value") when your Selenium version supports it. getAttribute() reads an attribute, and Selenium’s API may return a property value for some names; choose deliberately based on what the application contract requires. Selenium’s examples assert element text and input values in its waits documentation.
Use the failure message argument
JUnit assertions accept an optional failure message. It is shown when the assertion fails and should explain the expected behavior or the state being checked.
assertEquals("Approved", actualStatus, "status after approval");
For a computed failure message, JUnit also supports a message supplier overload. This can avoid building an expensive message when the assertion passes.
assertEquals(expected, actual,
() -> "Unexpected result for order " + orderId);
3. Wait before asserting dynamic browser state
A page may render an element or change its value after the initial navigation or click. Reading too soon can produce a stale value or a missing-element error. Wait for the condition required by the next operation, then read and assert the result.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
WebElement revealed = driver.findElement(By.id("revealed"));
driver.findElement(By.id("reveal")).click();
Wait<WebDriver> wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(d -> revealed.isDisplayed());
revealed.sendKeys("Displayed");
assertEquals("Displayed", revealed.getDomProperty("value"), "revealed input value");
This follows Selenium’s explicit-wait example: wait for visibility before interacting with the revealed input, then check its value. Replace the condition with the state your next step depends on, such as an element becoming clickable or a status message reaching expected text. See Selenium’s waiting strategies.
Explicit waits and implicit waits
- Explicit wait: waits for a stated condition in a specific part of the test. It documents what must be true before the next read or action.
- Implicit wait: configures WebDriver to wait when locating elements. Selenium documents this as a session-level setting.
- Fixed sleep: pauses for a chosen duration whether or not the condition has already become true. It can make a test slower when the page is fast and still fail when the page takes longer than the chosen delay.
Choose a wait based on the application behavior and the condition being checked. Selenium documents all three approaches; its examples do not establish one universal choice for every application. Avoid layering wait strategies without understanding their combined effect.
4. Assert expected exceptions with assertThrows
Use assertThrows when the test specifically verifies that an operation throws an exception of the expected type. It returns the caught exception, so you can make a separate assertion about its message or other details.
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
NoSuchElementException error = assertThrows(
NoSuchElementException.class,
() -> driver.findElement(By.id("not-present")));
assertEquals("no such element", error.getMessage().substring(0, 14));
The message assertion above is illustrative only: browser and driver exception text can vary. For robust tests, assert a stable application-specific exception detail only when the test contract requires it. If an element is expected to appear asynchronously, do not assert an immediate lookup failure; wait for its eventual state instead.
The message supplied to an assertion is different from the expected message thrown by the operation. For example, assertThrows(type, executable, "expected failure behavior") uses the string as the assertion’s failure message. To inspect the thrown exception’s message, assert against the returned exception separately:
MyException exception = assertThrows(
MyException.class,
() -> performOperation(),
"operation should reject invalid input");
assertEquals("invalid input", exception.getMessage());
JUnit describes this behavior in the JUnit Assertions API.
5. Write reliable assertions for browser tests
- Assert outcomes: check the resulting title, text, value, URL, or enabled state after the interaction.
- Wait for a meaningful condition: synchronize on the browser state needed by the assertion, not an arbitrary pause.
- Keep the assertion close to the action: failures are easier to diagnose when the action and expected result are visible together.
- Use stable expectations: avoid asserting volatile timestamps, generated IDs, or browser-specific exception wording unless those details are part of the requirement.
- Always close the driver: use cleanup such as
finallyor your test framework’s lifecycle hooks so the browser process is not left running after a failure.
6. Troubleshooting failed assertions
| Symptom | Likely cause | Fix |
|---|---|---|
| Expected text differs from actual text | The page has not reached its final state, or the selected element includes whitespace or different rendered text. | Wait for the intended state, inspect the exact value being read, and assert the user-visible content the test requires. |
NoSuchElementException before the assertion |
The locator is wrong, the element is in another context, or it has not appeared yet. | Check the locator and page/frame context. If appearance is asynchronous, wait for presence or visibility before reading. |
| Input value assertion is empty or stale | The test reads text content instead of the input’s value, or reads before the interaction completes. | Read the input’s DOM property named value and wait for the expected update when necessary. |
assertThrows reports that nothing was thrown |
The executable did not perform the failing operation, or the operation succeeded under the current page state. | Put the operation under test inside the lambda and verify the setup makes the failure expected. |
assertThrows reports the wrong exception type |
The failure occurred for a different reason, such as a stale element or invalid session. | Inspect the actual exception and correct the setup or expected type; do not broaden the expected type just to make the test pass. |
| Assertion passes locally but fails intermittently | The test reads a transient state or relies on timing. | Wait for a specific condition and assert the final observable result. Avoid fixed sleeps as the only synchronization. |
| Browser remains open after a failure | Driver cleanup did not run after the assertion aborted the test. | Put driver.quit() in a finally block or a test lifecycle cleanup method. |
7. Performance, reliability, and cost
Assertions themselves are usually a small part of browser-test runtime; navigation, browser startup, and waiting for application behavior can dominate. Keep waits tied to relevant conditions and avoid unnecessary fixed delays. Reuse a browser session only when test isolation remains clear, and always clean it up.
For reliability, assert stable observable behavior and report useful failure messages. A passing assertion confirms only the state it reads at that moment; it does not prove every browser, driver, or application configuration behaves identically. Verify your dependency and browser setup against their current project documentation.
JUnit and Selenium provide the testing and browser automation pieces. Capturing screenshots for visual review is a separate task. ScreenshotNeo is a website screenshot API and MCP server for developers; it can capture a page as PNG, JPEG, WebP, or PDF. Its response identifies page verdict and billing status. Screenshot capture does not replace assertions about DOM values or application behavior.
Or skip the browser setup
If your task is to capture a page image rather than assert DOM behavior, ScreenshotNeo takes one GET request with a URL. The ScreenshotNeo API documentation covers its 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 and removed before capture, along with known newsletter popups and chat widgets; each step can be turned off.
- Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed.
- An MCP server provides
take_screenshot,get_page_info, andcapture_pdftools for AI agents. - 1,000 screenshots a month are free with no card; paid plans start at $5 for 3,000 screenshots.
Sign up for ScreenshotNeo’s free plan to get 1,000 screenshots a month with no card.
Frequently asked questions
How do I use JUnit assertions in Selenium?
Read the browser state after an action and pass it as the actual value to a JUnit assertion. For example, compare driver.getTitle() with the expected title using assertEquals.
How do I assert text in Selenium WebDriver with Java?
Locate the element, read its rendered text with getText(), and compare that string to the expected text. Wait first if the page updates asynchronously.
When should I use assertThrows?
Use it when throwing the expected exception is the behavior being tested. If the browser element should eventually appear, wait for it and assert its state instead.
Where can I check JUnit assertion overloads?
Use the official JUnit Jupiter Assertions API for method signatures and overloads.


