webapp-selenium-testing

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Web Application Testing with Selenium WebDriver & Java

基于Selenium WebDriver & Java的Web应用测试

This skill enables comprehensive browser-based test automation for web applications using Selenium WebDriver within a Java/Maven environment. It provides patterns for Page Object Model, explicit waits, fluent assertions, and CI-ready test infrastructure.
Activation: This skill is triggered when you need to create Selenium tests, debug browser automation, implement Page Objects, or set up Java test infrastructure.
本技能可在Java/Maven环境中,借助Selenium WebDriver实现Web应用的全流程浏览器自动化测试。它提供了页面对象模型(Page Object Model)、显式等待、流畅断言以及适用于CI环境的测试基础设施模式。
触发条件: 当你需要创建Selenium测试、调试浏览器自动化脚本、实现页面对象或搭建Java测试基础设施时,将触发本技能。

When to Use This Skill

适用场景

Use this skill when you need to:
  • Create Selenium WebDriver tests using Java (JUnit 5)
  • Implement Page Object Model (POM) architecture
  • Handle synchronization with Explicit Waits (
    WebDriverWait
    )
  • Verify UI behavior with AssertJ Soft Assertions
  • Debug failing browser tests or DOM interactions
  • Set up Maven test infrastructure for a new project
  • Capture screenshots for reporting or debugging
  • Validate complex user flows and form submissions
  • Test across multiple browsers (Chrome, Firefox, Edge)
  • Integrate with Allure reporting
在以下场景中使用本技能:
  • 使用Java(JUnit 5)创建Selenium WebDriver测试
  • 实现页面对象模型(POM)架构
  • 通过显式等待(
    WebDriverWait
    )处理同步问题
  • 使用AssertJ软断言验证UI行为
  • 调试失败的浏览器测试或DOM交互问题
  • 为新项目搭建Maven测试基础设施
  • 捕获截图用于报告或调试
  • 验证复杂用户流程和表单提交
  • 在多浏览器(Chrome、Firefox、Edge)中执行测试
  • 与Allure报告工具集成

Prerequisites

前置依赖

ComponentVersionPurpose
Java JDK21+Runtime with modern features (Records, Pattern Matching)
Maven3.9+Dependency management and build
Selenium WebDriver4.xBrowser automation (includes Selenium Manager)
JUnit 55.10+Test framework
AssertJ3.xFluent assertions with Soft Assertions
Lombok1.18+Boilerplate reduction (@Slf4j, @Builder)
Note: Selenium Manager (included in Selenium 4.6+) automatically handles browser driver binaries - no manual driver setup required.

组件版本用途
Java JDK21+支持现代特性(Records、Pattern Matching)的运行时环境
Maven3.9+依赖管理与构建工具
Selenium WebDriver4.x浏览器自动化工具(内置Selenium Manager)
JUnit 55.10+测试框架
AssertJ3.x支持软断言的流畅断言库
Lombok1.18+减少样板代码(@Slf4j、@Builder)
注意: Selenium 4.6+内置的Selenium Manager可自动管理浏览器驱动二进制文件,无需手动配置驱动。

Selenium WebDriver Tools Reference

Selenium WebDriver工具参考

Navigation & Browser Control

导航与浏览器控制

MethodPurposeExample
driver.get(url)
Navigate to URL
driver.get("http://localhost:3000")
driver.navigate().to(url)
Navigate with history
driver.navigate().to(url)
driver.navigate().back()
Go back in historyBrowser back button
driver.navigate().refresh()
Refresh pageReload current page
driver.switchTo().window(handle)
Switch tabs/windowsMulti-window handling
driver.switchTo().frame(element)
Switch to iframeIframe interactions
driver.switchTo().alert()
Handle alertsAccept/dismiss dialogs
方法用途示例
driver.get(url)
导航至指定URL
driver.get("http://localhost:3000")
driver.navigate().to(url)
带历史记录的导航
driver.navigate().to(url)
driver.navigate().back()
返回上一页模拟浏览器后退按钮
driver.navigate().refresh()
刷新页面重新加载当前页面
driver.switchTo().window(handle)
切换标签页/窗口多窗口处理
driver.switchTo().frame(element)
切换至iframe与iframe交互
driver.switchTo().alert()
处理弹窗确认/取消对话框

Element Interaction

元素交互

MethodPurposeExample
element.click()
Click elementButton, link clicks
element.sendKeys(text)
Enter textInput fields
element.clear()
Clear fieldClear before typing
new Select(element)
Dropdown handlingSelect by value/text
new Actions(driver)
Complex actionsDrag-drop, hover, right-click
方法用途示例
element.click()
点击元素按钮、链接点击
element.sendKeys(text)
输入文本输入框内容填写
element.clear()
清空输入框输入前清空内容
new Select(element)
下拉框处理通过值/文本选择选项
new Actions(driver)
复杂操作拖拽、悬停、右键点击

Verification

验证操作

MethodPurposeExample
element.isDisplayed()
Check visibilityVerify element shown
element.isEnabled()
Check enabled stateVerify button clickable
element.getText()
Get text contentRead element text
element.getAttribute(name)
Get attributeRead href, class, etc.
driver.getTitle()
Get page titleVerify page loaded
driver.getCurrentUrl()
Get current URLVerify navigation
方法用途示例
element.isDisplayed()
检查可见性验证元素是否显示
element.isEnabled()
检查启用状态验证按钮是否可点击
element.getText()
获取文本内容读取元素文本
element.getAttribute(name)
获取属性值读取href、class等属性
driver.getTitle()
获取页面标题验证页面是否加载完成
driver.getCurrentUrl()
获取当前URL验证导航结果

Screenshots & Debugging

截图与调试

MethodPurposeExample
TakesScreenshot
Capture screenshotEvidence on failure
driver.getPageSource()
Get HTML sourceDOM analysis
LogEntries
Browser console logsDebug JS errors

方法用途示例
TakesScreenshot
捕获截图失败时留存证据
driver.getPageSource()
获取HTML源码DOM分析
LogEntries
浏览器控制台日志调试JS错误

Core Capabilities

核心能力

1. Browser Automation

1. 浏览器自动化

  • Navigate URLs, handle tabs/windows, manage history
  • Click, type, clear, submit forms
  • Handle dropdowns (
    Select
    ), drag-drop, hover
  • Switch frames/iframes, handle alerts
  • Manage cookies
  • 导航URL、处理标签页/窗口、管理浏览历史
  • 点击、输入、清空、提交表单
  • 处理下拉框(
    Select
    )、拖拽、悬停操作
  • 切换框架/iframe、处理弹窗
  • 管理Cookie

2. Verification (AssertJ)

2. 验证(AssertJ)

  • Soft Assertions: Validate multiple fields, report all failures
  • Element state:
    isDisplayed()
    ,
    isEnabled()
    ,
    isSelected()
  • Text content, attributes, URL, page title
  • Collection assertions for lists/tables
  • 软断言:验证多个字段,一次性报告所有失败
  • 元素状态验证:
    isDisplayed()
    isEnabled()
    isSelected()
  • 文本内容、属性、URL、页面标题验证
  • 列表/表格的集合断言

3. Synchronization

3. 同步处理

  • Explicit Waits:
    WebDriverWait
    +
    ExpectedConditions
  • Wait for visibility, clickability, presence
  • Custom wait conditions
  • Never use
    Thread.sleep()
  • 显式等待
    WebDriverWait
    +
    ExpectedConditions
  • 等待元素可见、可点击、存在
  • 自定义等待条件
  • 禁止使用
    Thread.sleep()

4. Reporting & Debugging

4. 报告与调试

  • Screenshots on failure (Allure integration)
  • Browser console log capture
  • Page source extraction
  • @Step
    annotations for Allure reports

  • 失败时自动捕获截图(集成Allure)
  • 捕获浏览器控制台日志
  • 提取页面源码
  • 使用
    @Step
    注解生成Allure报告

Your Role

你的角色

You coordinate the entire Selenium WebDriver test creation process:
  1. Analyze: Understand test requirements and data needs
  2. Inspect: Identify locator strategies (prioritize
    id
    ,
    data-testid
    ,
    cssSelector
    )
  3. Design: Apply Page Object Model strictly
  4. Implement: Generate test with error handling and logging
  5. Verify: Ensure assertions use AssertJ fluent style

你将统筹Selenium WebDriver测试创建的全流程:
  1. 分析:理解测试需求与数据需求
  2. 定位:确定元素定位策略(优先使用
    id
    data-testid
    cssSelector
  3. 设计:严格遵循页面对象模型
  4. 实现:生成包含错误处理与日志的测试代码
  5. 验证:确保断言使用AssertJ的流畅风格

Step-by-Step Workflows

分步工作流

Workflow 1: Create New Selenium Test

工作流1:创建新的Selenium测试

  1. Analyze the requirement
    • Identify the user flow to test
    • List elements to interact with
    • Define expected outcomes
  2. Set up Page Objects (see Page Object Model Guide)
    • Create BasePage with common methods
    • Create specific Page class with locators
    • Implement action methods with
      @Step
  3. Implement test class
    • Extend BaseTest
    • Use
      @DisplayName
      ,
      @Tag
      ,
      @Severity
    • Use Soft Assertions for validations
  4. Run and validate
    bash
    mvn test -Dtest=YourTest -Dheadless=false
  1. 分析需求
    • 确定需要测试的用户流程
    • 列出需要交互的元素
    • 定义预期结果
  2. 搭建页面对象(参考页面对象模型指南
    • 创建包含通用方法的BasePage
    • 创建包含元素定位器的特定Page类
    • 实现带
      @Step
      注解的操作方法
  3. 实现测试类
    • 继承BaseTest
    • 使用
      @DisplayName
      @Tag
      @Severity
      注解
    • 使用软断言进行验证
  4. 运行与验证
    bash
    mvn test -Dtest=YourTest -Dheadless=false

Workflow 2: Debug Failing Test

工作流2:调试失败的测试

  1. Run in non-headless mode
    bash
    mvn test -Dtest=FailingTest -Dheadless=false
  2. Add screenshot capture
    java
    ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
  3. Check browser console logs
    java
    driver.manage().logs().get(LogType.BROWSER);
  4. Verify locator using browser DevTools
    javascript
    document.querySelector('[data-testid="element"]')
  5. Check wait conditions - increase timeout or change ExpectedCondition
  1. 以非无头模式运行
    bash
    mvn test -Dtest=FailingTest -Dheadless=false
  2. 添加截图捕获
    java
    ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
  3. 检查浏览器控制台日志
    java
    driver.manage().logs().get(LogType.BROWSER);
  4. 使用浏览器DevTools验证定位器
    javascript
    document.querySelector('[data-testid="element"]')
  5. 检查等待条件 - 增加超时时间或修改ExpectedCondition

Workflow 3: Set Up New Project

工作流3:搭建新项目

  1. Create Maven project structure
    Run: scripts/setup-maven-project.ps1 -ProjectName "my-tests"
  2. Configure dependencies in pom.xml
    • See scripts/pom-template.xml
  3. Create base classes
    • BasePage, BaseTest, WebDriverFactory
    • See Page Object Model Guide
  4. Configure parallel execution
    properties
    # src/test/resources/junit-platform.properties
    junit.jupiter.execution.parallel.enabled=true

  1. 创建Maven项目结构
    Run: scripts/setup-maven-project.ps1 -ProjectName "my-tests"
  2. 在pom.xml中配置依赖
    • 参考scripts/pom-template.xml
  3. 创建基础类
    • BasePage、BaseTest、WebDriverFactory
    • 参考页面对象模型指南
  4. 配置并行执行
    properties
    # src/test/resources/junit-platform.properties
    junit.jupiter.execution.parallel.enabled=true

Troubleshooting

故障排查

ProblemCauseSolution
Element not foundNot loaded yetUse
WebDriverWait
with
visibilityOfElementLocated
Stale element referenceDOM changedRe-locate element before interaction
Click interceptedOverlay blockingScroll into view or wait for overlay to close
Timeout exceptionElement never visibleVerify locator, check for iframes
Session not createdDriver/browser mismatchSelenium Manager handles this automatically
Flaky testsRace conditionsAdd proper waits, use stable locators

问题原因解决方案
元素未找到元素尚未加载使用
WebDriverWait
结合
visibilityOfElementLocated
陈旧元素引用DOM已变更交互前重新定位元素
点击被拦截遮罩层阻挡滚动至元素可见或等待遮罩层关闭
超时异常元素始终不可见验证定位器,检查是否存在iframe
会话创建失败驱动与浏览器版本不匹配Selenium Manager会自动处理该问题
测试不稳定竞争条件添加合理等待,使用稳定的定位器

Best Practices Checklist

最佳实践清单

Never use
Thread.sleep()
- Use explicit waits with
WebDriverWait
Implement Page Object Model - Separate locators from test logic ✅ Use Soft Assertions - Report all failures in one test run ✅ Prefer stable locators -
id
,
data-testid
, semantic CSS ✅ Add
@Step
annotations
- Document actions in Allure reports ✅ Clean up resources - Close driver in
@AfterEach
Keep tests independent - Each test runs in isolation ✅ Use
@DisplayName
- Human-readable test descriptions ✅ Generate dynamic data - Use
Faker
for test data

禁止使用
Thread.sleep()
- 使用
WebDriverWait
实现显式等待 ✅ 实现页面对象模型 - 将元素定位器与测试逻辑分离 ✅ 使用软断言 - 一次测试运行中报告所有失败 ✅ 优先使用稳定的定位器 -
id
data-testid
、语义化CSS选择器 ✅ 添加
@Step
注解
- 在Allure报告中记录操作步骤 ✅ 清理资源 - 在
@AfterEach
中关闭驱动 ✅ 保持测试独立性 - 每个测试用例独立运行 ✅ 使用
@DisplayName
- 设置易读的测试描述 ✅ 生成动态测试数据 - 使用
Faker
生成测试数据

Running Tests

运行测试

Maven Commands

Maven命令

CommandPurpose
mvn test
Run all tests
mvn test -Dtest=LoginTest
Run specific class
mvn test -Dtest=LoginTest#shouldLoginSuccessfully
Run specific method
mvn test -Dgroups=smoke
Run tagged tests
mvn test -Dheadless=true
Run headless (CI)
mvn allure:serve
Generate and view Allure report
命令用途
mvn test
运行所有测试
mvn test -Dtest=LoginTest
运行指定测试类
mvn test -Dtest=LoginTest#shouldLoginSuccessfully
运行指定测试方法
mvn test -Dgroups=smoke
运行标记的测试
mvn test -Dheadless=true
以无头模式运行(适用于CI环境)
mvn allure:serve
生成并查看Allure报告

CI/CD Integration

CI/CD集成示例

yaml
undefined
yaml
undefined

GitHub Actions example

GitHub Actions example

  • name: Run Selenium Tests run: mvn clean test -Dheadless=true -Dbrowser=chrome
  • name: Generate Allure Report run: mvn allure:report

---
  • name: Run Selenium Tests run: mvn clean test -Dheadless=true -Dbrowser=chrome
  • name: Generate Allure Report run: mvn allure:report

---

References

参考资料

  • Locator Strategies Guide - Selector priority and patterns
  • Page Object Model Guide - POM implementation with Java
  • Wait Strategies Guide - Explicit waits and ExpectedConditions
  • Maven POM Template - Standard dependency configuration
  • Project Setup Script - Scaffold new test project

  • 定位策略指南 - 选择器优先级与模式
  • 页面对象模型指南 - 基于Java的POM实现
  • 等待策略指南 - 显式等待与ExpectedConditions
  • Maven POM模板 - 标准依赖配置
  • 项目搭建脚本 - 快速搭建测试项目

Quick Commands

快速命令

TaskCommand/Pattern
Find by ID
By.id("elementId")
Find by test ID
By.cssSelector("[data-testid='name']")
Wait for visible
wait.until(ExpectedConditions.visibilityOfElementLocated(by))
Click safely
wait.until(ExpectedConditions.elementToBeClickable(by)).click()
Soft assert
SoftAssertions.assertSoftly(s -> { ... })
Take screenshot
((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE)
Run test
mvn test -Dtest=ClassName
任务命令/模式
通过ID定位元素
By.id("elementId")
通过test ID定位元素
By.cssSelector("[data-testid='name']")
等待元素可见
wait.until(ExpectedConditions.visibilityOfElementLocated(by))
安全点击元素
wait.until(ExpectedConditions.elementToBeClickable(by)).click()
软断言
SoftAssertions.assertSoftly(s -> { ... })
捕获截图
((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE)
运行测试
mvn test -Dtest=ClassName