Skip to main content

撰寫測試

簡介

Playwright 的斷言是為動態網頁特別設計的。檢查會自動重試,直到必要條件滿足為止。Playwright 內建自動等待機制,會在執行動作前等待元素可被操作。Playwright 提供多種 assertThat 多載來撰寫斷言。

請看以下範例,示範如何使用 web-first 斷言、定位器與選擇器來撰寫測試。

package org.example;

import java.util.regex.Pattern;
import com.microsoft.playwright.*;
import com.microsoft.playwright.options.AriaRole;

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;

public class App {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.chromium().launch();
Page page = browser.newPage();
page.navigate("https://playwright.dev");

// 期望標題「包含」某個子字串。
assertThat(page).hasTitle(Pattern.compile("Playwright"));

// 建立一個定位器
Locator getStarted = page.getByRole(AriaRole.LINK, new Page.GetByRoleOptions().setName("Get Started"));

// 期望屬性「嚴格等於」指定值。
assertThat(getStarted).hasAttribute("href", "/docs/intro");

// 點擊「Get started」連結。
getStarted.click();

// 期望頁面具有名稱為 Installation 的標題。
assertThat(page.getByRole(AriaRole.HEADING,
new Page.GetByRoleOptions().setName("Installation"))).isVisible();
}
}
}

斷言

Playwright 提供多種 assertThat 多載,會等待直到預期條件被滿足。

import java.util.regex.Pattern;
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;

assertThat(page).hasTitle(Pattern.compile("Playwright"));

定位器

定位器是 Playwright 自動等待與可重試能力的核心。定位器代表在任意時刻於頁面上尋找元素的方法,並用來對元素執行 .click.fill 等動作。你可以透過 Page.locator() 建立自訂定位器。

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;

Locator getStarted = page.locator("text=Get Started");

assertThat(getStarted).hasAttribute("href", "/docs/intro");
getStarted.click();

Playwright 支援多種不同類型的定位器,例如 roletexttest id 等。想了解有哪些定位器與如何選用,請參考這份深入指南

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;

assertThat(page.locator("text=Installation")).isVisible();

測試隔離

Playwright 具有 BrowserContext 的概念,這是一個記憶體中的隔離瀏覽器設定檔。建議為每個測試建立新的 BrowserContext,以確保它們不會互相干擾。

Browser browser = playwright.chromium().launch();
BrowserContext context = browser.newContext();
Page page = context.newPage();

接下來做什麼