跳到主要內容

編寫測試

簡介

Playwright 斷言是專為動態網路所建立。檢查會自動重試,直到符合必要條件。Playwright 內建自動等待功能,表示它會先等待元素變成可操作狀態,再執行動作。Playwright 提供 assertThat 多載來編寫斷言。

請參考以下範例測試,了解如何使用以網路優先的斷言、定位器和選取器來編寫測試。

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.org.tw");

// Expect a title "to contain" a substring.
assertThat(page).hasTitle(Pattern.compile("Playwright"));

// create a locator
Locator getStarted = page.getByRole(AriaRole.LINK, new Page.GetByRoleOptions().setName("Get Started"));

// Expect an attribute "to be strictly equal" to the value.
assertThat(getStarted).hasAttribute("href", "/docs/intro");

// Click the get started link.
getStarted.click();

// Expects page to have a heading with the name of 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 支援許多不同的定位器,例如 role texttest 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();

下一步