Web-First Assertions
TestFly provides web-first assertions inspired by Playwright's expect() and AssertJ. All DOM and page assertions poll via WebDriverWait until the condition is met or the timeout is exceeded (the AI assertions are the exception: they do not poll). You never need to write manual waits or Thread.sleep() before asserting.
import static io.testfly.assertion.SeleniumAssert.assertThat;
// Or directly in BaseTest, BasePage, BaseJUnit5Test, and BaseCucumberSteps:
assertThat(By.id("dashboard")).isVisible();
Why Web-First Assertions?
Traditional assertions (like TestNG Assert.assertTrue(el.isDisplayed()) or JUnit assertTrue) evaluate the condition immediately at a single moment in time. If the element is still animating, fetching data, or rendering, the test fails spuriously.
TestFly's assertThat():
- Auto-retries during the configured
timeouts.explicit(default 10s). - Logs each step automatically into
StepLoggerand surfaces it in the HTML report. - Accepts both Selenium
Byand fluentLocatorinstances ($(),getByRole(), etc.).
Which element is checked
countcounts every match, visible or hidden, for bothByandLocator(the same numberLocator.count()returns).- The other matchers check a single element. With a
By, that is the first match. With aLocator, the whole chain (filter,withText,nth, ...) is resolved again on each poll and the first visible match is checked; if no match is visible, the first match is checked. This way hidden duplicates (for example a mobile and a desktop menu) do not hide the visible one, and hidden elements such asinput[type=hidden]can still be checked withhasValueorhasAttribute. - Assertions do not apply
locators.strict: several matches are not an error.
Available Matchers
Visibility
assertThat(By.id("welcome-banner")).isVisible();
assertThat(By.cssSelector(".spinner")).isHidden();
Text
// Exact match against the element's text, with leading/trailing whitespace trimmed
assertThat(By.tagName("h1")).hasText("Dashboard");
// Substring containment
assertThat(By.id("greeting")).containsText("Welcome back");
Interactability & State
assertThat(By.id("submit-btn")).isEnabled();
assertThat(By.id("delete-btn")).isDisabled();
assertThat(By.id("terms-checkbox")).isChecked();
assertThat(By.id("search-input")).isFocused();
isEnabled and isDisabled also require the element to be displayed; a hidden element fails with actual: [not displayed]. isChecked reads the selected state of a native checkbox, radio button or <option>.
Verified Click
assertThat(...).click() clicks the element and asserts that the click really reached it:
assertThat(headerLoginButton).click();
assertThat(submitButton).as("Submit order").click();
Behind the scenes it:
- Finds the element exactly like
locator.click()does, including chain filters (nth,filter,withText) and self-healing, and waits until it is visible and enabled. - Scrolls it to the centre of the viewport and moves the mouse onto it. A submit button at the bottom of a long form is brought into view first.
- Waits until nothing covers it, such as a cookie banner, a modal or a sticky header.
- Clicks it and checks that the
clickevent was delivered to the element. - Logs a passed
Clicked: ...step in the report.
If a step fails, the error says which one, for example:
Click not performed: element not visible and enabled: By.id: login (No element found for: By.id: login)
Click not performed: By.id: login is covered by <div class='cookie-banner'> (timeout: 10s)
Click did not reach By.id: login (no click event was received)
Finding the element uses timeouts.explicit, like locator.click(). within(...) applies to the later steps, such as waiting for a covering element to go away.
In soft mode (softly() / softAssert(...)) the failure is recorded and the test continues. If the click navigates away or opens an alert, it counts as delivered and the alert is left open.
assertThat(...).click() only proves that the click reached the element. To prove the app reacted, assert on the result, for example assertThatPage().urlContains("/login") or assertThat(loginModal).isVisible(). The plain locator.click() action is unchanged.
Verified Fill & Clear
assertThat(...).fill(text) types into a field and asserts that the value really stuck. assertThat(...).clear() does the same for an empty value:
assertThat(userNameField).fill("admin");
assertThat(passwordField).fill(System.getenv("APP_PASSWORD"));
assertThat(searchField).clear();
Behind the scenes it:
- Finds the element like
locator.fill()does (chain filters, self-healing) and waits until it is visible and enabled. - Waits until it is not
readonly, then scrolls it to the centre of the viewport. - Clears it and types the text, exactly like
locator.fill(). - Waits until the value equals the text, and checks again after a short pause. This catches values that
maxlength, an input mask, or the app's own state (React, Vue, ...) changed or reset after typing. - Logs a passed
Filled: ... with [admin]orCleared: ...step.
Example failures:
Fill not performed: element is read-only: By.id: username (timeout: 10s)
Fill did not stick for By.id: code: expected value [abcdef] but was [abc] (timeout: 10s)
Fill did not stick for By.id: password: expected 7 characters but got 0 (password value hidden) (timeout: 10s)
For type="password" fields the value never appears in the report or in failure messages; only its length does.
The value must match exactly. A field that reformats its input, such as a phone mask that turns 5321234567 into (532) 123 45 67, fails this assertion. For such fields use locator.fill(...) and then assertThat(field).hasValue("(532) 123 45 67").
Attributes & CSS
// Attribute value match
assertThat(By.name("username")).hasValue("admin");
assertThat(By.id("link")).hasAttribute("target", "_blank");
// Attribute presence check (regardless of value)
assertThat(By.id("btn")).hasAttribute("disabled");
// CSS property check
assertThat(By.id("error-toast")).hasCssValue("color", "rgb(255, 0, 0)");
// CSS class membership
assertThat(By.id("item")).hasClass("active");
Form Inputs & Validation
Input fields have no visible text, so hasText() does not work on them. Assert on their value instead:
// Value checks
assertThat(passwordField).hasValue(); // any non-empty value
assertThat(searchField).hasEmptyValue();
assertThat(emailField).containsValue("@example.com");
assertThat(phoneField).valueMatches("\\+90 \\d{3} \\d{3} \\d{4}");
// Password masking ("show password" toggle)
assertThat(passwordField).isPasswordHidden(); // type="password"
showPasswordToggle.click();
assertThat(passwordField).isPasswordVisible(); // type is no longer "password"
// Input attributes
assertThat(usernameField).hasType("text").hasPlaceholder("Username").hasMaxLength(20);
assertThat(usernameField).isRequired(); // required or aria-required="true"
assertThat(usernameField).isEditable(); // visible, enabled, not readonly
assertThat(referenceField).isReadOnly();
// HTML5 constraint validation
assertThat(emailField).isInvalid().hasValidationMessage("@");
assertThat(emailField).isValid();
hasValidationMessage() checks the browser's own message, which depends on the browser and its locale.
To read an input's value in your code, use locator.getValue(). getText() always returns "" for inputs.
Text Patterns & Lists
assertThat(By.id("order")).hasTextMatching("Order #\\d+ placed");
assertThat(By.id("status")).hasTextIgnoringCase("active");
// All matching elements, in order / in any order
assertThat($(".breadcrumb li")).hasTexts("Home", "Products", "Shoes");
assertThat($(".tag")).containsTexts("java", "selenium");
Selection
assertThat(By.id("newsletter")).not().isChecked();
assertThat(By.id("select-all")).isIndeterminate();
assertThat(By.cssSelector("option[value='tr']")).isSelected();
assertThat(By.id("country")).hasSelectedOption("Turkey");
assertThat(By.id("country")).hasOptions("Germany", "Turkey", "USA");
Accessibility & Identity
assertThat(By.id("search")).hasRole("searchbox").hasAccessibleName("Search products");
assertThat(By.cssSelector("main > section")).hasId("results");
assertThat(By.id("footer-cta")).isInViewport();
Negation with not()
not() negates the next assertion, like Playwright's not():
assertThat(By.id("status")).not().hasText("Error");
assertThat(By.id("status")).not().containsText("failed");
assertThat(By.name("username")).not().hasValue("guest");
assertThat(By.id("submit")).not().containsClass("loading");
assertThat(By.id("submit")).not().hasAttribute("disabled");
assertThat(By.id("email")).not().hasAttribute("aria-invalid", "true");
assertThat(By.id("search")).not().isFocused();
assertThat(By.id("newsletter")).not().isChecked();
assertThat(By.id("error-banner")).not().isAttached(); // no element in the DOM
not()applies only to the assertion right after it. InassertThat(x).not().isVisible().hasText("a"),hasTextis not negated.- As in Playwright, most negated assertions also pass when no element matches. To require the element too, assert it first:
assertThat(status).isVisible().not().hasText("Error"). not()cannot be combined withclick(),fill()orclear().- Failure messages and report steps show the negation:
Expected NOT text [Error] for: ...,[not] Assert text 'Error' ....
Element Count & Presence
assertThat(By.cssSelector("table tbody tr")).count(5);
assertThat($(".card")).count(3); // hidden cards are counted too
assertThat($(".card")).countAtLeast(1).countAtMost(10);
assertThat(By.id("csrf-token")).isAttached(); // present, visible or not (alias: exists())
assertThat(By.id("error-banner")).not().isAttached(); // absent from the DOM
When you assert on a Locator ($(), getByRole(), ...), only visible elements are matched. So count, hasCount, exists and isAttached ignore hidden elements. Pass a By if hidden elements must be counted.
Page & URL (PageAssert)
Assert on page title and URL with automatic wait retry — no manual getDriver().getTitle() or getCurrentUrl() with raw TestNG/JUnit assertions required:
// Title checks
assertThat(getDriver()).hasTitle("Dashboard");
assertThat(getDriver()).titleContains("Sauce");
assertThatPage().hasTitle("Products");
// URL checks
assertThat(getDriver()).hasUrl("https://example.com/dashboard");
assertThat(getDriver()).urlContains("/inventory");
assertThat(getDriver()).urlMatches(".*\\/orders\\/\\d+");
// With custom message & timeout
assertThat(getDriver())
.as("Should land on dashboard after login")
.within(Duration.ofSeconds(5))
.urlContains("/dashboard");
// Alerts (the alert is left open)
assertThatPage().hasAlert().hasAlertText("Saved successfully");
assertThatPage().hasNoAlert();
// Cookies & localStorage
assertThatPage().hasCookie("session").hasCookie("locale", "tr");
assertThatPage().doesNotHaveCookie("tracking");
assertThatPage().hasLocalStorageItem("theme", "dark");
// Windows / tabs
assertThatPage().hasWindowCount(2);
// Negation: not() negates the next page assertion
assertThatPage().not().urlContains("/login");
assertThatPage().not().hasTitle("Error");
As with LocatorAssert, not() applies only to the next assertion. A negated assertion passes as soon as the condition is not met, so right after a click that navigates, assert the new state first (urlContains("/inventory")) instead of only not().urlContains("/login").
Playwright Parity
TestFly's element assertions follow the names of Playwright for Java (assertThat(locator).isVisible()), not the JavaScript names (expect(locator).toBeVisible()):
| Playwright JS | TestFly |
|---|---|
expect(l).toBeAttached() | assertThat(l).isAttached() |
toBeChecked() / toBeChecked({indeterminate: true}) | isChecked() / isIndeterminate() |
toBeDisabled() / toBeEnabled() / toBeEditable() | isDisabled() / isEnabled() / isEditable() |
toBeEmpty() | isEmpty() |
toBeFocused() | isFocused() |
toBeHidden() / toBeVisible() | isHidden() / isVisible() |
toBeInViewport({ratio}) | isInViewport() / isInViewport(ratio) |
toContainText(text | regex | array) | containsText(String | Pattern | String[]) |
toContainClass(...) | containsClass(String | List<String>) |
toHaveAccessibleName/Description/ErrorMessage | hasAccessibleName / hasAccessibleDescription / hasAccessibleErrorMessage (String or Pattern) |
toHaveAttribute(name, value | regex) | hasAttribute(name, String | Pattern) |
toHaveClass(regex) | hasClass(Pattern) |
toHaveCount(n) | hasCount(n) |
toHaveCSS(name, value | regex) | hasCSS(name, String | Pattern) |
toHaveId(...) | hasId(String | Pattern) |
toHaveJSProperty(name, value) | hasJSProperty(name, value) |
toHaveRole(role) | hasRole(Role.BUTTON) / hasRole("button") |
toHaveText(text | regex | array) | hasText(String | Pattern | String[] | Pattern[]) |
toHaveValue(...) / toHaveValues([...]) | hasValue(String | Pattern) / hasValues(...) |
.not | .not() |
isEmpty() checks the value of input, textarea and select (a value of spaces is not empty) and the trimmed text content of any other element.
Pattern arguments match anywhere in the value, as Playwright's regular expressions do. Use ^...$ for a full match: hasText(Pattern.compile("^Order #\\d+$")).
Differences from Playwright:
hasClass(String)checks a single class name, which is what Playwright callscontainsClass. To match the wholeclassattribute, usehasClass(Pattern).- Playwright's option objects have no counterpart. Use
within(...)fortimeout,not()forvisible: false/enabled: false/checked: false, andhasTextIgnoringCase(...)forignoreCase. toMatchAriaSnapshotand element screenshots are not available. For page screenshots, see visual testing.
Modifiers & Customization
Custom Timeout (within)
Override the default timeouts.explicit duration for slow-loading components (such as report exports or large file uploads), or for quick dismissals:
// Using Duration
assertThat(By.id("export-ready-toast"))
.within(Duration.ofSeconds(30))
.isVisible();
// Using seconds shorthand
assertThat(By.id("quick-tooltip"))
.within(2)
.isVisible();
Descriptive Failure Messages (as)
Attach contextual information to explain why an assertion was made:
assertThat(By.id("user-avatar"))
.as("User profile picture after OAuth login")
.isVisible();
// If it fails: "[User profile picture after OAuth login] Expected element to be visible: By.id: user-avatar (actual: [not found], timeout: 10s)"
describedAs(...) is an alias for as(...). Page assertions (assertThat(getDriver()), assertThatPage()) report the current title and URL instead: (actual title: [...], actual url: [...], timeout: ...).
What actual reports
Every failure ends with (actual: [...], timeout: ...) showing the last value observed while polling. A negated assertion (not()) ends with (condition still met, timeout: ...) instead, and click(), fill() and clear() say which step failed (see Verified Click).
| Assertion | actual shows |
|---|---|
hasText, containsText | the element's text, quoted, on one line (max 200 chars) |
hasValue | the value, quoted, or null when the element has none |
hasAttribute(name, value) | name="...", or attribute 'name' absent |
hasAttribute(name) | attribute 'name' absent |
hasCssValue | property="..." |
hasClass | class="..." |
isVisible, isHidden | not displayed, displayed |
isEnabled, isDisabled | not displayed, disabled, enabled |
isChecked | not selected |
isFocused | focused element: <input#other> |
count | the number of elements found, e.g. 2 element(s) |
countAtLeast, countAtMost | the number of elements found, e.g. 2 element(s) |
isAttached, exists | not found |
hasTexts, containsTexts, hasText(Pattern[]), containsText(String[]) | the texts of all matches, e.g. ["Apple", "Pear"] |
hasRole | the role, or generic (no role) |
hasAccessibleName, hasAccessibleDescription | the computed name or description, quoted |
Other single-element assertions (hasValue(Pattern), isEditable, ...) | the element checked, e.g. condition not met on <input#email> |
Every single-element matcher reports not found when nothing matches, and element went stale when the page replaced the element during the check.
If a Locator cannot be resolved, for example because the container of $(".row").within(By.id("grid")) never appears or nth(5) is out of range, the assertion fails with a normal AssertionError (actual: [locator failed: ...]) instead of a LocatorException.
Soft Assertions (softAssert)
When you want to perform multiple checks without terminating the test on the first failure, use Soft Assertions. The framework collects all failures and marks the test failed at the end, reporting all issues together.
TestFly supports three fluent ways to use soft assertions:
1. Direct softAssert(locator)
Available as a built-in helper in BaseTest, BasePage, BaseJUnit5Test, and BaseCucumberSteps:
softAssert(By.id("username")).hasValue("johndoe");
softAssert(By.id("status-badge")).hasText("Active");
// Test continues even if username or email fails.
// Framework flushes and reports all failures at test completion.
Page state works the same way: softAssert(getDriver()).hasTitle("Dashboard") or softAssertPage().urlContains("/orders").
2. Fluent .softly() Modifier
assertThat(By.id("header")).softly().hasText("Dashboard");
assertThat(By.id("avatar")).softly().isVisible();
3. Via softAssert().assertThat(locator)
softAssert().assertThat(By.id("total")).hasText("$100.00");
You can still use raw boolean soft assertions when needed:
softAssert().that(items.size() > 0, "Item list should not be empty");
Accessibility assertions
getByRole(...) finds elements by their role and name. These assertions check the same
things on an element you already have, deterministically and without an LLM:
assertThat(By.id("save")).hasRole(Role.BUTTON);
assertThat(By.id("save")).hasAccessibleName("Save order"); // exact, whitespace collapsed
assertThat(By.id("save")).hasAccessibleName(Pattern.compile("(?i)save")); // partial, ignores case
assertThat(By.id("email")).hasAccessibleDescription("We never share it");
assertThat(By.id("email")).hasAccessibleDescription(Pattern.compile("never share"));
They retry until the timeout like every other assertion, and a failure shows what was found:
Expected element to have role [button]: By.id: save (actual: [link], timeout: 10s).
ARIA snapshots
matchesAriaSnapshot compares the whole accessibility tree under an element with a YAML
template, so one assertion covers structure, names and states:
assertThat(By.tagName("nav")).matchesAriaSnapshot("""
- navigation "Main":
- link "Home"
- link "Docs"
""");
You do not have to write templates by hand. Print the current tree, review it, and paste it in:
System.out.println(find("nav").ariaSnapshot()); // one element
System.out.println(ariaSnapshot()); // whole page, inside a page object
A template is a constraint, not a full copy of the tree:
| Template | Matches |
|---|---|
- button | any button |
- button "Save" | a button whose name contains Save, ignoring case |
- heading /Issues \d+/ | a heading whose name matches the regular expression (add i after the closing / to ignore case) |
- heading [level=2] | a heading with that attribute |
- checkbox "Milk" [checked] | a checked checkbox; other attributes are disabled, expanded, pressed, selected |
- list: followed by an indented list | children that appear in this order among the direct children; other children are ignored |
The top-level entries match the children of the element, or of any element below it, so a
template can describe only the part you care about. Only the roles of
getByRole and text appear; other elements are transparent and their
children belong to the nearest ancestor that has a role. Hidden content
(aria-hidden, display: none, hidden) and decorative images (alt="") are left out.
A mistake in the template (an unknown role, invalid YAML) fails immediately with
IllegalArgumentException instead of waiting for the timeout. A mismatch prints the
template and the captured snapshot (at most 200 lines).
The accessible name is TestFly's simplified version of the W3C algorithm. It uses the same
order as withName(...): aria-label, aria-labelledby, a <label>, the visible text for
roles that take their name from content (button, link, heading, cell and similar), then
alt, title, a button's value and placeholder. Shadow DOM is not entered.
Semantic AI Assertions (satisfiesAi & violatesAi)
For complex page states, dynamic messages, or visual flows where exact string matching is brittle, TestFly provides LLM-evaluated semantic assertions:
// Page-level semantic check
assertThatPage().satisfiesAi("Shopping cart summary displays total price and at least 1 item");
assertThatPage().violatesAi("Error banner, access denied, or 500 server notice");
// Convenience shortcut in BaseTest/BasePage
assertWithAi("The user profile shows active subscription status");
// Element-level semantic check
assertThat(find(".status-pill")).satisfiesAi("Indicates a successful payment");
For full details, anti-throttle guarantees, and examples, see the Agentic Testing & Autonomous AI Guide.
Assertion Boundary: Primitive Data Assertions
TestFly's assertThat() is intentionally specialized for Web & DOM elements with automatic retries and polling.
For standard Java primitive data checks (e.g. assertEquals(user.getAge(), 30) or list size assertions), we recommend using AssertJ or your test runner's built-in assertions (TestNG / JUnit 5) alongside TestFly. TestFly intentionally does not reinvent general-purpose assertion libraries to prevent API bloat and keep your test architecture clean and modular.