Selenium WebDriver drives the browser; JUnit or TestNG supplies the test lifecycle, assertions, and organization. Here are Java examples for both frameworks, including setup, a browser check, cleanup, dependencies, and how to run the tests.
What each part of a Selenium test does
A typical Java browser test creates a WebDriver session, navigates and performs actions, checks an observable result, then closes the session. WebDriver handles browser communication; the test framework handles the test method, pass/fail assertions, lifecycle hooks, and test execution. Selenium’s component guide explains the division of responsibilities.
The examples below use Selenium’s sample web form and ChromeDriver. They illustrate test structure; they are not a report of an independently executed test. Your machine or CI environment must have a compatible browser and driver setup.
JUnit Jupiter Selenium example
JUnit Jupiter uses @BeforeEach and @AfterEach to create and release a driver for each test. The test checks the page title, enters text, submits the form, and checks the response.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Scan for outdated or missing drivers - takes under a minute3Repair Windows errors before they cause bigger problems#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
class SeleniumFormTest {
private WebDriver driver;
@BeforeEach
void setUp() {
driver = new ChromeDriver();
}
@Test
void submitsWebForm() {
driver.get("https://www.selenium.dev/selenium/web/web-form.html");
assertEquals("Web form", driver.getTitle());
driver.findElement(By.name("my-text")).sendKeys("Selenium");
driver.findElement(By.cssSelector("button")).click();
assertEquals("Received!", driver.findElement(By.id("message")).getText());
}
@AfterEach
void tearDown() {
if (driver != null) {
driver.quit();
}
}
}
The title assertion verifies navigation; the final assertion verifies the form outcome. Selectors and page content are tied to Selenium’s sample page, so replace them with locators and expected behavior from the application under test.
TestNG Selenium example
TestNG uses method-level lifecycle hooks and its own assertion class. alwaysRun = true on teardown is useful when cleanup should run even if a preceding test configuration step fails.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class SeleniumFormTest {
private WebDriver driver;
@BeforeMethod
public void setUp() {
driver = new ChromeDriver();
}
@Test
public void submitsWebForm() {
driver.get("https://www.selenium.dev/selenium/web/web-form.html");
Assert.assertEquals(driver.getTitle(), "Web form");
driver.findElement(By.name("my-text")).sendKeys("Selenium");
driver.findElement(By.cssSelector("button")).click();
Assert.assertEquals(driver.findElement(By.id("message")).getText(), "Received!");
}
@AfterMethod(alwaysRun = true)
public void tearDown() {
if (driver != null) {
driver.quit();
}
}
}
This is an adaptation of the Selenium browser-test pattern, not a Selenium-published TestNG class. Check annotation attributes and runner setup against the TestNG version selected for your project; the TestNG documentation covers lifecycle hooks and runner features.
Set up dependencies and run the test
Add Selenium and the relevant test framework to the project’s Maven or Gradle build, then use the build tool’s test task. Selenium’s library installation guide shows dependency configuration, and its Java examples guide describes running examples with Maven, including mvn test.
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
- Choose a framework. Include JUnit Jupiter and its test engine for the JUnit class, or TestNG for the TestNG class. Do not include only Selenium and expect it to provide test annotations or assertions.
- Place the class where the build discovers tests. Follow the Maven or Gradle test-source conventions and ensure the chosen runner/engine is configured.
- Run the test task. For a Maven project configured for the class, run
mvn testfrom the project root. Use the corresponding Gradle test task if the project uses Gradle. - Check the test report and browser environment. A dependency declaration does not prove that a test ran; confirm the runner discovered the method and that the browser session started.
Dependency versions change. Selenium’s downloads page listed Java Selenium 4.49.0 as stable on September 9, 2026; verify the current release and choose framework versions compatible with the project rather than copying a version number blindly. Selenium downloads.
Lifecycle, isolation, and parallel execution
Use per-test drivers when isolation matters
A fresh browser session in each setup hook keeps cookies, local storage, and page state from leaking between test methods. Always call quit() in teardown to release the session, including after failures. Avoid placing cleanup only at the end of the test body: an assertion or browser exception could bypass it.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
JUnit lifecycle scope
JUnit Jupiter’s @BeforeEach and @AfterEach run around each test. The JUnit 5.0.2 guide says @BeforeAll and @AfterAll normally need to be static unless the per-class test-instance lifecycle is selected. That lifecycle detail is versioned documentation; consult the guide matching the JUnit version in your build. JUnit 5.0.2 User Guide.
TestNG data and parallel behavior
TestNG documents data providers for supplying multiple input sets and configuration for parallel execution. Parallel browser tests need separate driver instances per test or thread; sharing one mutable WebDriver can make navigation and assertions interfere. Configure concurrency deliberately and confirm the browser and test environment can support it. TestNG documentation.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Choosing JUnit or TestNG
Neither framework is universally better for Selenium. Selenium’s Java guidance identifies both as runner choices, notes JUnit’s broad use, and points to TestNG’s parallel and parameterized-test capabilities. Compare the needs of the suite and the conventions already supported by the team’s build and IDE.
| Decision point | JUnit Jupiter | TestNG |
|---|---|---|
| Per-test lifecycle in these examples | @BeforeEach and @AfterEach |
@BeforeMethod and @AfterMethod |
| Assertions shown | JUnit Assertions.assertEquals |
TestNG Assert.assertEquals |
| Inputs and execution features covered by cited framework guidance | JUnit lifecycle and test-runner guidance | Data providers and parallel execution configuration |
| Best fit | When the project already uses JUnit conventions and its lifecycle is sufficient | When TestNG’s data-provider or parallel configuration fits existing suite needs |
Troubleshooting common failures
- No tests run: Confirm the test source location, class/method discovery conventions, and that the JUnit engine or TestNG runner is configured in the build.
- Browser fails to start: Check that Chrome is installed in the execution environment and that Selenium can provision or locate a compatible driver. Review the startup exception before changing test assertions.
- Driver process remains after a failure: Ensure teardown is recognized by the selected framework and calls
driver.quit(); retain the null check if setup can fail before assigning the field. - Element lookup fails: Verify the page loaded, that the test is on the expected page, and that the locator matches the current markup. The sample selectors apply to Selenium’s demonstration page, not arbitrary sites.
- TestNG annotations are not recognized: Verify the TestNG dependency and imports, then check the selected TestNG version’s annotation and runner configuration.
- Tests interfere during parallel runs: Do not share a WebDriver across concurrent methods. Use isolated sessions and tune parallelism to available browser resources.
Or skip the browser setup
For a screenshot rather than an interactive Selenium test, ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns an image or PDF; this cURL example saves a WebP screenshot. See the ScreenshotNeo API documentation for request options.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
ScreenshotNeo accepts cookie and consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be disabled. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for AI agents. The Free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.
ScreenshotNeo captures pages; it does not replace Selenium when a test must click through an application and assert behavior.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteQuick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




