webapp-selenium-testing
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseWeb 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
前置依赖
| Component | Version | Purpose |
|---|---|---|
| Java JDK | 21+ | Runtime with modern features (Records, Pattern Matching) |
| Maven | 3.9+ | Dependency management and build |
| Selenium WebDriver | 4.x | Browser automation (includes Selenium Manager) |
| JUnit 5 | 5.10+ | Test framework |
| AssertJ | 3.x | Fluent assertions with Soft Assertions |
| Lombok | 1.18+ | Boilerplate reduction (@Slf4j, @Builder) |
Note: Selenium Manager (included in Selenium 4.6+) automatically handles browser driver binaries - no manual driver setup required.
| 组件 | 版本 | 用途 |
|---|---|---|
| Java JDK | 21+ | 支持现代特性(Records、Pattern Matching)的运行时环境 |
| Maven | 3.9+ | 依赖管理与构建工具 |
| Selenium WebDriver | 4.x | 浏览器自动化工具(内置Selenium Manager) |
| JUnit 5 | 5.10+ | 测试框架 |
| AssertJ | 3.x | 支持软断言的流畅断言库 |
| Lombok | 1.18+ | 减少样板代码(@Slf4j、@Builder) |
注意: Selenium 4.6+内置的Selenium Manager可自动管理浏览器驱动二进制文件,无需手动配置驱动。
Selenium WebDriver Tools Reference
Selenium WebDriver工具参考
Navigation & Browser Control
导航与浏览器控制
| Method | Purpose | Example |
|---|---|---|
| Navigate to URL | |
| Navigate with history | |
| Go back in history | Browser back button |
| Refresh page | Reload current page |
| Switch tabs/windows | Multi-window handling |
| Switch to iframe | Iframe interactions |
| Handle alerts | Accept/dismiss dialogs |
| 方法 | 用途 | 示例 |
|---|---|---|
| 导航至指定URL | |
| 带历史记录的导航 | |
| 返回上一页 | 模拟浏览器后退按钮 |
| 刷新页面 | 重新加载当前页面 |
| 切换标签页/窗口 | 多窗口处理 |
| 切换至iframe | 与iframe交互 |
| 处理弹窗 | 确认/取消对话框 |
Element Interaction
元素交互
| Method | Purpose | Example |
|---|---|---|
| Click element | Button, link clicks |
| Enter text | Input fields |
| Clear field | Clear before typing |
| Dropdown handling | Select by value/text |
| Complex actions | Drag-drop, hover, right-click |
| 方法 | 用途 | 示例 |
|---|---|---|
| 点击元素 | 按钮、链接点击 |
| 输入文本 | 输入框内容填写 |
| 清空输入框 | 输入前清空内容 |
| 下拉框处理 | 通过值/文本选择选项 |
| 复杂操作 | 拖拽、悬停、右键点击 |
Verification
验证操作
| Method | Purpose | Example |
|---|---|---|
| Check visibility | Verify element shown |
| Check enabled state | Verify button clickable |
| Get text content | Read element text |
| Get attribute | Read href, class, etc. |
| Get page title | Verify page loaded |
| Get current URL | Verify navigation |
| 方法 | 用途 | 示例 |
|---|---|---|
| 检查可见性 | 验证元素是否显示 |
| 检查启用状态 | 验证按钮是否可点击 |
| 获取文本内容 | 读取元素文本 |
| 获取属性值 | 读取href、class等属性 |
| 获取页面标题 | 验证页面是否加载完成 |
| 获取当前URL | 验证导航结果 |
Screenshots & Debugging
截图与调试
| Method | Purpose | Example |
|---|---|---|
| Capture screenshot | Evidence on failure |
| Get HTML source | DOM analysis |
| Browser console logs | Debug JS errors |
| 方法 | 用途 | 示例 |
|---|---|---|
| 捕获截图 | 失败时留存证据 |
| 获取HTML源码 | DOM分析 |
| 浏览器控制台日志 | 调试JS错误 |
Core Capabilities
核心能力
1. Browser Automation
1. 浏览器自动化
- Navigate URLs, handle tabs/windows, manage history
- Click, type, clear, submit forms
- Handle dropdowns (), drag-drop, hover
Select - 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: +
WebDriverWaitExpectedConditions - Wait for visibility, clickability, presence
- Custom wait conditions
- Never use
Thread.sleep()
- 显式等待:+
WebDriverWaitExpectedConditions - 等待元素可见、可点击、存在
- 自定义等待条件
- 禁止使用
Thread.sleep()
4. Reporting & Debugging
4. 报告与调试
- Screenshots on failure (Allure integration)
- Browser console log capture
- Page source extraction
- annotations for Allure reports
@Step
- 失败时自动捕获截图(集成Allure)
- 捕获浏览器控制台日志
- 提取页面源码
- 使用注解生成Allure报告
@Step
Your Role
你的角色
You coordinate the entire Selenium WebDriver test creation process:
- Analyze: Understand test requirements and data needs
- Inspect: Identify locator strategies (prioritize ,
id,data-testid)cssSelector - Design: Apply Page Object Model strictly
- Implement: Generate test with error handling and logging
- Verify: Ensure assertions use AssertJ fluent style
你将统筹Selenium WebDriver测试创建的全流程:
- 分析:理解测试需求与数据需求
- 定位:确定元素定位策略(优先使用、
id、data-testid)cssSelector - 设计:严格遵循页面对象模型
- 实现:生成包含错误处理与日志的测试代码
- 验证:确保断言使用AssertJ的流畅风格
Step-by-Step Workflows
分步工作流
Workflow 1: Create New Selenium Test
工作流1:创建新的Selenium测试
-
Analyze the requirement
- Identify the user flow to test
- List elements to interact with
- Define expected outcomes
-
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
-
Implement test class
- Extend BaseTest
- Use ,
@DisplayName,@Tag@Severity - Use Soft Assertions for validations
-
Run and validatebash
mvn test -Dtest=YourTest -Dheadless=false
-
分析需求
- 确定需要测试的用户流程
- 列出需要交互的元素
- 定义预期结果
-
搭建页面对象(参考页面对象模型指南)
- 创建包含通用方法的BasePage
- 创建包含元素定位器的特定Page类
- 实现带注解的操作方法
@Step
-
实现测试类
- 继承BaseTest
- 使用、
@DisplayName、@Tag注解@Severity - 使用软断言进行验证
-
运行与验证bash
mvn test -Dtest=YourTest -Dheadless=false
Workflow 2: Debug Failing Test
工作流2:调试失败的测试
-
Run in non-headless modebash
mvn test -Dtest=FailingTest -Dheadless=false -
Add screenshot capturejava
((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); -
Check browser console logsjava
driver.manage().logs().get(LogType.BROWSER); -
Verify locator using browser DevToolsjavascript
document.querySelector('[data-testid="element"]') -
Check wait conditions - increase timeout or change ExpectedCondition
-
以非无头模式运行bash
mvn test -Dtest=FailingTest -Dheadless=false -
添加截图捕获java
((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); -
检查浏览器控制台日志java
driver.manage().logs().get(LogType.BROWSER); -
使用浏览器DevTools验证定位器javascript
document.querySelector('[data-testid="element"]') -
检查等待条件 - 增加超时时间或修改ExpectedCondition
Workflow 3: Set Up New Project
工作流3:搭建新项目
-
Create Maven project structure
Run: scripts/setup-maven-project.ps1 -ProjectName "my-tests" -
Configure dependencies in pom.xml
- See scripts/pom-template.xml
-
Create base classes
- BasePage, BaseTest, WebDriverFactory
- See Page Object Model Guide
-
Configure parallel executionproperties
# src/test/resources/junit-platform.properties junit.jupiter.execution.parallel.enabled=true
-
创建Maven项目结构
Run: scripts/setup-maven-project.ps1 -ProjectName "my-tests" -
在pom.xml中配置依赖
- 参考scripts/pom-template.xml
-
创建基础类
- BasePage、BaseTest、WebDriverFactory
- 参考页面对象模型指南
-
配置并行执行properties
# src/test/resources/junit-platform.properties junit.jupiter.execution.parallel.enabled=true
Troubleshooting
故障排查
| Problem | Cause | Solution |
|---|---|---|
| Element not found | Not loaded yet | Use |
| Stale element reference | DOM changed | Re-locate element before interaction |
| Click intercepted | Overlay blocking | Scroll into view or wait for overlay to close |
| Timeout exception | Element never visible | Verify locator, check for iframes |
| Session not created | Driver/browser mismatch | Selenium Manager handles this automatically |
| Flaky tests | Race conditions | Add proper waits, use stable locators |
| 问题 | 原因 | 解决方案 |
|---|---|---|
| 元素未找到 | 元素尚未加载 | 使用 |
| 陈旧元素引用 | DOM已变更 | 交互前重新定位元素 |
| 点击被拦截 | 遮罩层阻挡 | 滚动至元素可见或等待遮罩层关闭 |
| 超时异常 | 元素始终不可见 | 验证定位器,检查是否存在iframe |
| 会话创建失败 | 驱动与浏览器版本不匹配 | Selenium Manager会自动处理该问题 |
| 测试不稳定 | 竞争条件 | 添加合理等待,使用稳定的定位器 |
Best Practices Checklist
最佳实践清单
✅ Never use - Use explicit waits with
✅ Implement Page Object Model - Separate locators from test logic
✅ Use Soft Assertions - Report all failures in one test run
✅ Prefer stable locators - , , semantic CSS
✅ Add annotations - Document actions in Allure reports
✅ Clean up resources - Close driver in
✅ Keep tests independent - Each test runs in isolation
✅ Use - Human-readable test descriptions
✅ Generate dynamic data - Use for test data
Thread.sleep()WebDriverWaitiddata-testid@Step@AfterEach@DisplayNameFaker✅ 禁止使用 - 使用实现显式等待
✅ 实现页面对象模型 - 将元素定位器与测试逻辑分离
✅ 使用软断言 - 一次测试运行中报告所有失败
✅ 优先使用稳定的定位器 - 、、语义化CSS选择器
✅ 添加注解 - 在Allure报告中记录操作步骤
✅ 清理资源 - 在中关闭驱动
✅ 保持测试独立性 - 每个测试用例独立运行
✅ 使用 - 设置易读的测试描述
✅ 生成动态测试数据 - 使用生成测试数据
Thread.sleep()WebDriverWaitiddata-testid@Step@AfterEach@DisplayNameFakerRunning Tests
运行测试
Maven Commands
Maven命令
| Command | Purpose |
|---|---|
| Run all tests |
| Run specific class |
| Run specific method |
| Run tagged tests |
| Run headless (CI) |
| Generate and view Allure report |
| 命令 | 用途 |
|---|---|
| 运行所有测试 |
| 运行指定测试类 |
| 运行指定测试方法 |
| 运行标记的测试 |
| 以无头模式运行(适用于CI环境) |
| 生成并查看Allure报告 |
CI/CD Integration
CI/CD集成示例
yaml
undefinedyaml
undefinedGitHub 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
快速命令
| Task | Command/Pattern |
|---|---|
| Find by ID | |
| Find by test ID | |
| Wait for visible | |
| Click safely | |
| Soft assert | |
| Take screenshot | |
| Run test | |
| 任务 | 命令/模式 |
|---|---|
| 通过ID定位元素 | |
| 通过test ID定位元素 | |
| 等待元素可见 | |
| 安全点击元素 | |
| 软断言 | |
| 捕获截图 | |
| 运行测试 | |