テストの作成
イントロダクション
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.dokyumento.jp");
// 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 は、ロール、テキスト、テスト 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();