# TestFly Part 12: Playwright-style assertions in Selenium with not(), ARIA snapshots and strict mode

URL: https://hakangul.lovable.app/blog/testfly-part-12-playwright-style-assertions-aria-snapshots-strict-mode
Author: Hakan Gül — Team Lead Senior Test Automation Engineer
Published: 2026-10-12
Updated: 2026-10-18
Category: test-automation
Tags: TestFly, Selenium, Playwright, Accessibility, ARIA, Java, SDET

> TestFly 1.1.0 brings Playwright for Java's assertion style to Selenium: a chainable not(), deterministic hasRole()/hasAccessibleName() checks, YAML-based matchesAriaSnapshot(), and an opt-in strict mode that fails loudly when a locator is ambiguous.

## English

TestFly 1.1.0 closes most of the gap with Playwright for Java's assertion API without leaving Selenium. `LocatorAssert.not()` negates the next check. `hasRole()`, `hasAccessibleName()` and `hasAccessibleDescription()` read the real accessibility tree instead of guessing from DOM attributes. `matchesAriaSnapshot()` compares a subtree against a Playwright-style YAML template. The opt-in `locators.strict` setting makes an ambiguous locator fail loudly, where before it would silently click the wrong element.

## Why Selenium assertions need not()

In classic Selenium/TestNG code a negative assertion usually means one of two bad options: wrap the positive assertion in a `try/catch` and invert the result, or write a separate polling loop that waits for a condition to stay false. Either way the intent of the test ends up buried in boilerplate.

TestFly's `LocatorAssert` now has the same `not()` as Playwright for Java. It negates only the assertion that comes directly after it in the chain:

```java
import io.testfly.test.BaseTest;
import org.testng.annotations.Test;

import static io.testfly.assertion.Assertions.assertThat;

public class CheckoutErrorTest extends BaseTest {

    @Test
    public void testErrorBannerClearsAfterRetry() {
        open("/checkout");
        find("#pay-btn").click();

        assertThat(find("#error-banner")).hasText("Payment declined");

        find("#retry-btn").click();

        // Only the assertion right after not() is negated
        assertThat(find("#error-banner")).not().isVisible();
        assertThat(find("#spinner")).not().isAttached();
    }
}
```

As in Playwright, most negated assertions also pass when no matching element exists, so `not().isVisible()` passes whether the banner is hidden or removed from the DOM. If the element has to exist and only be in a different state, assert presence first: `assertThat(status).isVisible().not().hasText("Error")`. You cannot combine `not()` with the verified actions `click()`, `fill()` or `clear()`.

## Deterministic accessibility assertions

TestFly already had `hasAriaLabel`-style attribute checks. Version 1.1.0 adds assertions that read the computed accessibility tree the way a screen reader does. They run through one bundled probe script, with no axe-core injection and no LLM call:

```java
@Test
public void testSubmitButtonIsAccessible() {
    open("/signup");

    assertThat(find("#submit"))
        .hasRole(Role.BUTTON)
        .hasAccessibleName("Create account");

    assertThat(find("#email"))
        .hasAccessibleDescription(Pattern.compile("(?i)required"));
}
```

`hasRole(Role | String)` checks the explicit `role` attribute or the implicit role of the HTML tag. `hasAccessibleName` and `hasAccessibleDescription` take either an exact `String` (whitespace collapsed, with the same matching `Locator.withName(...)` uses) or a `Pattern` for a partial or case-insensitive match. Only the 36 standard ARIA `Role` values and visible text are reported. Decorative images and hidden content are skipped, and the probe does not enter Shadow DOM.

## How ARIA snapshots work

`matchesAriaSnapshot()` is TestFly's version of Playwright's `toMatchAriaSnapshot()`. It captures the accessibility subtree under a locator and compares it with a YAML template. The comparison is partial and ordered, so it does not need a full serialization of the subtree to match.

```java
@Test
public void testNavigationLandmarkStructure() {
    open("/dashboard");

    assertThat(By.tagName("nav")).matchesAriaSnapshot("""
        - link "Home"
        - link "Docs"
        - button "Account" [expanded=false]
        """);
}
```

The matching rules follow Playwright:

| Rule | Behavior |
|---|---|
| Role | must match exactly |
| Quoted name | case-insensitive substring match |
| `/regex/` name | matched with `find()` |
| `[attribute]` / `[level=2]` | every template attribute must be present on the page; extra page attributes are ignored |

A malformed template fails at once with `IllegalArgumentException`, without waiting for the timeout. When the assertion fails, the error contains both the template and the captured snapshot, so you can see the difference without re-running anything. To write a template in the first place, print what TestFly currently sees:

```java
System.out.println(find("nav").ariaSnapshot());
// or, for the whole page:
System.out.println(ariaSnapshot());
```

Then paste the printed YAML into the test and trim it down to the nodes that matter.

## How strict mode catches silent multi-element bugs

By default, when a locator resolves to several visible elements, TestFly does what classic Selenium does and silently clicks or reads the first one. That is how a renamed CSS class or an A/B-tested duplicate banner produces a test that passes against the wrong element for weeks before anyone notices.

You turn strict mode on per project:

```yaml
# testfly.yml
locators:
  strict: true
```

With `locators.strict: true`, an action on a locator that matches more than one visible element, and that was not narrowed with `first()`, `nth()` or `last()`, throws immediately:

```
Strict mode violation: css=".card .btn-buy" resolved to 3 visible elements;
use first()/nth()/last() or narrow the locator. Candidates: <button.btn-buy#card-1>, <button.btn-buy#card-2>, <button.btn-buy#card-3>
```

`isVisible()` and `isEnabled()` report the same violation instead of silently checking the first match. `count()`, `elements()` and `assertThat(...)` (for counting or enumerating) are not affected, because multiple matches are expected there. When strict mode flags a locator, narrow it explicitly:

```java
find(".card .btn-buy").nth(1).click();          // second card, explicit
find(".card").filter(withText("Pro Plan"))
             .find(".btn-buy").click();          // narrowed by content instead
```

Hidden duplicates, such as a closed mobile nav next to the desktop one or a hidden modal clone, are filtered out before the check runs, so responsive layouts don't cause false strict-mode violations.

## FAQ

### Does `not()` replace the existing Selenium assertion methods?

No. `not()` is a modifier on `LocatorAssert`. It negates whichever assertion comes right after it in the same chain, and all existing positive assertions stay as they are.

### Do the accessibility assertions require axe-core or an external library?

No. `hasRole`, `hasAccessibleName`, `hasAccessibleDescription` and `matchesAriaSnapshot` use one bundled probe script that reads the browser's computed accessibility tree directly. There is no axe-core injection and no LLM call.

### Will enabling `locators.strict` break existing tests?

It can, and that is intended. Any locator that used to match more than one visible element silently now fails explicitly. The fix is the one Playwright recommends: narrow the locator with `first()`, `nth()`, `last()` or a more specific selector.

### Does strict mode affect `count()` or `elements()`?

No. Those methods exist to work with multiple matches, so strict mode does not apply to them. It applies only to actions (`click`, `fill`, …) and to the boolean checks `isVisible()`/`isEnabled()`.

## Türkçe

TestFly 1.1.0, Selenium'u bırakmadan Playwright for Java'nın assertion API'siyle arasındaki farkı kapatıyor. `LocatorAssert.not()` zincirdeki bir sonraki kontrolü tersine çeviriyor. `hasRole()` / `hasAccessibleName()` / `hasAccessibleDescription()` DOM attribute'larından tahmin yürütmek yerine gerçek erişilebilirlik ağacını okuyor. `matchesAriaSnapshot()` bir alt ağacı Playwright tarzı bir YAML şablonuyla karşılaştırıyor. Opsiyonel `locators.strict` ayarı açıkken birden fazla elemana uyan bir locator, yanlış elemana sessizce tıklamak yerine açık bir hatayla duruyor.

## Selenium assertion'larında not() neden gerekli

Klasik Selenium/TestNG kodunda negatif assertion yazmanın genelde iki kötü yolu vardır: pozitif assertion'ı `try/catch` içine alıp sonucu ters çevirmek ya da bir koşulun yanlış kalmasını bekleyen ayrı bir polling döngüsü yazmak. İkisinde de testin asıl niyeti boilerplate arasında kaybolur.

TestFly'ın `LocatorAssert` sınıfında artık Playwright for Java'daki `not()` var. Zincirde yalnızca kendisinden hemen sonra gelen assertion'ı tersine çevirir:

```java
import io.testfly.test.BaseTest;
import org.testng.annotations.Test;

import static io.testfly.assertion.Assertions.assertThat;

public class CheckoutErrorTest extends BaseTest {

    @Test
    public void testErrorBannerClearsAfterRetry() {
        open("/checkout");
        find("#pay-btn").click();

        assertThat(find("#error-banner")).hasText("Payment declined");

        find("#retry-btn").click();

        // Yalnızca not()'tan hemen sonraki assertion negatife döner
        assertThat(find("#error-banner")).not().isVisible();
        assertThat(find("#spinner")).not().isAttached();
    }
}
```

Playwright'ta olduğu gibi, tersine çevrilmiş assertion'ların çoğu eşleşen eleman hiç yoksa da geçer. Yani `not().isVisible()`, banner gizlenmiş de olsa DOM'dan tamamen silinmiş de olsa sağlanır. Elemanın var olması ama farklı bir durumda olması gerekiyorsa önce varlığını doğrulayın: `assertThat(status).isVisible().not().hasText("Error")`. `not()`, doğrulamalı `click()`, `fill()` ve `clear()` aksiyonlarıyla birlikte kullanılamaz.

## Deterministik erişilebilirlik assertion'ları

TestFly'da `hasAriaLabel` tarzı attribute kontrolleri zaten vardı. 1.1.0 sürümü, erişilebilirlik ağacının hesaplanmış halini bir ekran okuyucunun okuduğu şekilde okuyan assertion'lar ekliyor. Hepsi tek bir gömülü probe script üzerinden çalışıyor; axe-core enjekte edilmiyor, LLM çağrısı yapılmıyor:

```java
@Test
public void testSubmitButtonIsAccessible() {
    open("/signup");

    assertThat(find("#submit"))
        .hasRole(Role.BUTTON)
        .hasAccessibleName("Create account");

    assertThat(find("#email"))
        .hasAccessibleDescription(Pattern.compile("(?i)required"));
}
```

`hasRole(Role | String)`, açıkça verilmiş `role` attribute'unu ya da HTML etiketinin örtük rolünü kontrol eder. `hasAccessibleName` ve `hasAccessibleDescription` iki tür girdi alır: tam eşleşme için bir `String` (boşluklar sadeleştirilir, eşleştirme `Locator.withName(...)` ile aynıdır) ya da kısmi veya büyük/küçük harf duyarsız eşleşme için bir `Pattern`. Yalnızca 36 standart ARIA `Role` değeri ve görünür metin raporlanır. Dekoratif görseller ve gizli içerik atlanır, Shadow DOM'un içine girilmez.

## ARIA snapshot'lar nasıl çalışır

`matchesAriaSnapshot()`, Playwright'taki `toMatchAriaSnapshot()`'ın TestFly karşılığı. Bir locator'ın altındaki erişilebilirlik alt ağacını yakalar ve bir YAML şablonuyla karşılaştırır. Karşılaştırma kısmi ve sıralıdır; alt ağacın tamamını birebir serileştirip kıyaslamaz.

```java
@Test
public void testNavigationLandmarkStructure() {
    open("/dashboard");

    assertThat(By.tagName("nav")).matchesAriaSnapshot("""
        - link "Home"
        - link "Docs"
        - button "Account" [expanded=false]
        """);
}
```

Eşleşme kuralları Playwright'taki mantığı izler:

| Kural | Davranış |
|---|---|
| Rol | tam olarak eşleşmeli |
| Tırnaklı isim | büyük/küçük harf duyarsız alt dize eşleşmesi |
| `/regex/` isim | `find()` ile eşleştirilir |
| `[attribute]` / `[level=2]` | şablondaki her attribute sayfada bulunmalı; sayfadaki fazla attribute'lar yok sayılır |

Bozuk bir şablon, timeout beklenmeden hemen `IllegalArgumentException` fırlatır. Assertion başarısız olursa hata mesajında hem şablon hem yakalanan snapshot yer alır, farkı görmek için testi yeniden koşmanız gerekmez. İlk şablonu yazmak için TestFly'ın o anda ne gördüğünü yazdırın:

```java
System.out.println(find("nav").ariaSnapshot());
// ya da tüm sayfa için:
System.out.println(ariaSnapshot());
```

Ardından çıkan YAML'ı teste yapıştırıp yalnızca önemli düğümleri bırakın.

## Strict mode, birden fazla elemana uyan locator hatalarını nasıl önler

Varsayılan durumda bir locator birden fazla görünür elemana uyduğunda TestFly da klasik Selenium gibi ilkine sessizce tıklar ya da ilkini okur. Adı değişen bir CSS sınıfı ya da A/B testi yüzünden iki kez görünen bir banner, testin haftalarca yanlış eleman üzerinde geçmesine böyle yol açar ve kimse fark etmez.

Strict mode proje bazında açılır:

```yaml
# testfly.yml
locators:
  strict: true
```

`locators.strict: true` ayarlıyken, birden fazla görünür elemana uyan ve `first()`, `nth()` ya da `last()` ile daraltılmamış bir locator üzerinde yapılan aksiyon anında hata fırlatır:

```
Strict mode violation: css=".card .btn-buy" resolved to 3 visible elements;
use first()/nth()/last() or narrow the locator. Candidates: <button.btn-buy#card-1>, <button.btn-buy#card-2>, <button.btn-buy#card-3>
```

`isVisible()` ve `isEnabled()` de ilk eşleşmeye sessizce bakmak yerine aynı ihlali bildirir. `count()`, `elements()` ve sayma/listeleme amaçlı `assertThat(...)` bundan etkilenmez, çünkü orada birden fazla eşleşme zaten beklenen durumdur. Strict mode bir ihlal yakaladığında locator'ı açıkça daraltın:

```java
find(".card .btn-buy").nth(1).click();          // ikinci kart, açıkça belirtilmiş
find(".card").filter(withText("Pro Plan"))
             .find(".btn-buy").click();          // içeriğe göre daraltılmış
```

Gizli kopyalar, örneğin masaüstü menünün yanında duran kapalı mobil menü ya da gizli bir modal klonu, kontrolden önce elenir. Bu sayede responsive layout'lar yanlış strict mode ihlali üretmez.

## SSS

### not(), mevcut Selenium assertion metodlarının yerini mi alıyor?

Hayır. `not()`, `LocatorAssert` üzerindeki bir değiştiricidir ve aynı zincirde kendisinden hemen sonra gelen assertion'ı tersine çevirir. Mevcut pozitif assertion'ların hepsi olduğu gibi kalır.

### Erişilebilirlik assertion'ları axe-core ya da harici bir kütüphane gerektiriyor mu?

Hayır. `hasRole`, `hasAccessibleName`, `hasAccessibleDescription` ve `matchesAriaSnapshot`, tarayıcının hesapladığı erişilebilirlik ağacını doğrudan okuyan tek bir gömülü probe script kullanır. axe-core enjekte edilmez, LLM çağrısı yapılmaz.

### locators.strict'i açmak mevcut testleri bozar mı?

Bozabilir ve bu bilinçli bir tercih. Daha önce sessizce birden fazla görünür elemana uyan her locator artık açık bir hata verir. Çözüm Playwright'ın önerdiğiyle aynı: locator'ı `first()`, `nth()`, `last()` ya da daha belirgin bir seçiciyle daraltmak.

### Strict mode, count() veya elements()'i etkiler mi?

Hayır. Bu metodlar zaten birden fazla eşleşmeyle çalışmak için var, strict mode onlara uygulanmaz. Yalnızca aksiyonlarda (`click`, `fill`, …) ve `isVisible()`/`isEnabled()` boolean kontrollerinde devreye girer.
