编写测试
简介
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");
// 期望标题 “包含” 一个子字符串。
assertThat(page).hasTitle(Pattern.compile("Playwright"));
// 创建一个定位器
Locator getStarted = page.getByRole(AriaRole.LINK, new Page.GetByRoleOptions().setName("Get Started"));
// 期望一个属性 “严格等于” 该值。
assertThat(getStarted).hasAttribute("href", "/docs/intro");
// 点击开始链接。
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 支持多种不同的定位器,如 角色定位器、文本定位器、测试 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();