编写测试
介绍
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.net.cn");
// 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();