メインコンテンツにスキップ

テストの記述

はじめに

Playwrightのアサーションは、動的なウェブのために特別に作成されています。必要な条件が満たされるまで、チェックは自動的に再試行されます。Playwrightには、要素が操作可能になるまで待機するオートウェイト機能が組み込まれています。Playwrightは、アサーションを記述するためのassertThatオーバーロードを提供します。

Webファーストのアサーション、ロケーター、セレクターを使用してテストを記述する方法を学ぶには、以下のテスト例をご覧ください。

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();

次は何ですか