AgentSkillsCN

webapp-selenium-testing

利用 Selenium WebDriver 4+ 结合 Java 21+ 与 JUnit 5,打造浏览器自动化测试工具集。适用于需要创建、调试或运行 Selenium 测试、实现页面对象模型、运用 WebDriverWait 处理显式等待、截取屏幕截图、通过 AssertJ 断言验证 UI 元素、测试表单、验证用户流程,或搭建 Maven 测试项目的情况。支持 Chrome、Firefox 和 Edge 等主流浏览器。

SKILL.md
--- frontmatter
name: webapp-selenium-testing
description: Browser automation toolkit using Selenium WebDriver 4+ with Java 21+ and JUnit 5. Use when asked to create, debug, or run Selenium tests, implement Page Object Model, handle explicit waits with WebDriverWait, capture screenshots, verify UI elements with AssertJ assertions, test forms, validate user flows, or set up Maven test projects. Supports Chrome, Firefox, and Edge browsers.

Web Application Testing with Selenium WebDriver & Java

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.

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

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.


Selenium WebDriver Tools Reference

Navigation & Browser Control

MethodPurposeExample
driver.get(url)Navigate to URLdriver.get("http://localhost:3000")
driver.navigate().to(url)Navigate with historydriver.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

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

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

Screenshots & Debugging

MethodPurposeExample
TakesScreenshotCapture screenshotEvidence on failure
driver.getPageSource()Get HTML sourceDOM analysis
LogEntriesBrowser console logsDebug JS errors

Core Capabilities

1. Browser Automation

  • 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

2. Verification (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

3. Synchronization

  • Explicit Waits: WebDriverWait + ExpectedConditions
  • Wait for visibility, clickability, presence
  • Custom wait conditions
  • Never use Thread.sleep()

4. Reporting & Debugging

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

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

Step-by-Step Workflows

Workflow 1: Create New Selenium Test

  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
    

Workflow 2: Debug Failing Test

  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

Workflow 3: Set Up New Project

  1. Create Maven project structure

    code
    Run: scripts/setup-maven-project.ps1 -ProjectName "my-tests"
    
  2. Configure dependencies in pom.xml

  3. Create base classes

  4. Configure parallel execution

    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

Best Practices Checklist

Never use Thread.sleep() - Use explicit waits with WebDriverWaitImplement 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 @AfterEachKeep tests independent - Each test runs in isolation ✅ Use @DisplayName - Human-readable test descriptions ✅ Generate dynamic data - Use Faker for test data


Running Tests

Maven Commands

CommandPurpose
mvn testRun all tests
mvn test -Dtest=LoginTestRun specific class
mvn test -Dtest=LoginTest#shouldLoginSuccessfullyRun specific method
mvn test -Dgroups=smokeRun tagged tests
mvn test -Dheadless=trueRun headless (CI)
mvn allure:serveGenerate and view Allure report

CI/CD Integration

yaml
# GitHub Actions example
- name: Run Selenium Tests
  run: mvn clean test -Dheadless=true -Dbrowser=chrome
  
- name: Generate Allure Report
  run: mvn allure:report

References


Quick Commands

TaskCommand/Pattern
Find by IDBy.id("elementId")
Find by test IDBy.cssSelector("[data-testid='name']")
Wait for visiblewait.until(ExpectedConditions.visibilityOfElementLocated(by))
Click safelywait.until(ExpectedConditions.elementToBeClickable(by)).click()
Soft assertSoftAssertions.assertSoftly(s -> { ... })
Take screenshot((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE)
Run testmvn test -Dtest=ClassName