编写测试
简介
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("http://playwright.dev");
// 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"));
定位器
Locators 是 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、text、test 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();