[ PROMPT_NODE_25030 ]
assertions
[ SKILL_DOCUMENTATION ]
# Playwright Java – 断言参考
## 导入语句
java
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
import org.assertj.core.api.SoftAssertions;
---
## 定位器断言(自动重试)
Playwright 的 `assertThat(locator)` 会自动轮询(直到 `defaultTimeout`)。
**始终优先使用这些断言,而不是 `locator.isVisible()` + `assertTrue`。**
java
// 可见性
assertThat(locator).isVisible();
assertThat(locator).isHidden();
// 启用 / 禁用
assertThat(locator).isEnabled();
assertThat(locator).isDisabled();
// 文本内容(精确或部分匹配)
assertThat(locator).hasText("Exact text");
assertThat(locator).containsText("partial");
assertThat(locator).hasText(Pattern.compile("Order #\d+"));
// 多个元素
assertThat(locator).hasCount(5);
assertThat(locator).hasText(new String[]{"Item A", "Item B", "Item C"});
// 属性
assertThat(locator).hasAttribute("aria-expanded", "true");
assertThat(locator).hasAttribute("href", Pattern.compile(".*\/dashboard"));
// CSS 类
assertThat(locator).hasClass("active");
assertThat(locator).hasClass(Pattern.compile("btn-.*"));
// 输入值
assertThat(locator).hasValue("expected input value");
assertThat(locator).hasValue(Pattern.compile("\d{4}-\d{2}-\d{2}")); // 日期模式
// 选中状态 (复选框/单选框)
assertThat(locator).isChecked();
assertThat(locator).not().isChecked();
// 焦点
assertThat(locator).isFocused();
// 可编辑
assertThat(locator).isEditable();
---
## 页面断言
java
// URL
assertThat(page).hasURL("https://example.com/dashboard");
assertThat(page).hasURL(Pattern.compile(".*/dashboard"));
// 标题
assertThat(page).hasTitle("Dashboard – MyApp");
assertThat(page).hasTitle(Pattern.compile(".*Dashboard.*"));
---
## 取反
java
// 添加 .not() 进行反向断言
assertThat(locator).not().isVisible();
assertThat(locator).not().hasText("Error");
assertThat(page).not().hasURL(Pattern.compile(".*/login"));
---
## 自定义断言超时
java
assertThat(locator)
.hasText("Loaded", new LocatorAssertions.HasTextOptions().setTimeout(10_000));
---
## 软断言 (AssertJ)
在报告前收集所有失败信息 — 对表单验证测试至关重要:
java
@Test
void shouldDisplayAllProfileFields() {
ProfilePage profile = new ProfilePage(page());
profile.navigate();
SoftAssertions soft = new SoftAssertions();
soft.assertThat(profile.getNameField().inputValue()).isEqualTo("Amal"