October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk6 min

JUnit 5 Annotations in Selenium: A Java Tutorial with Examples

A practical Java guide to JUnit Jupiter annotations in Selenium: create a fresh WebDriver per test, assert browser behavior, clean up reliably, and understand parameterized and class-level lifecycle options.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use JUnit Jupiter’s @BeforeEach and @AfterEach to create and quit a Selenium WebDriver around each test, and put browser actions and assertions in @Test methods. This pattern keeps each test’s browser state isolated and ensures the session is cleaned up. The examples below use JUnit 5 (Jupiter), not JUnit 4.

How to use JUnit 5 annotations with Selenium WebDriver

JUnit Jupiter annotations define when a Selenium test runs and when its browser resources are created or released. The core annotations are generally in org.junit.jupiter.api. A Jupiter test class can initialize a driver before each test, use it in a test method, and quit it afterward.

This example follows the Java interaction pattern in the Selenium WebDriver documentation. It opens Selenium’s sample web form, checks its title, enters text, submits it, and checks the confirmation.

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.time.Duration;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

class WebFormTest {
    private WebDriver driver;

    @BeforeEach
    void setUp() {
        driver = new ChromeDriver();
    }

    @Test
    @DisplayName("submits text and shows a confirmation")
    void submitsTextAndShowsConfirmation() {
        driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
        driver.get("https://www.selenium.dev/selenium/web/web-form.html");

        assertEquals("Web form", driver.getTitle());

        WebElement textBox = driver.findElement(By.name("my-text"));
        WebElement submitButton = driver.findElement(By.cssSelector("button"));
        textBox.sendKeys("Selenium");
        submitButton.click();

        assertEquals("Received!", driver.findElement(By.id("message")).getText());
    }

    @AfterEach
    void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}

The sample’s 500-millisecond implicit wait is the value used in Selenium’s published example, not a universal setting. If your application renders elements asynchronously, synchronize on the condition the test actually needs and use a consistent wait strategy; adding arbitrary delays can make tests slower without making them reliable.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • 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.

What @BeforeEach and @AfterEach do in a Selenium test

@BeforeEach runs before every test method invocation, including each invocation of a parameterized test. In the example it creates a fresh ChromeDriver. @AfterEach runs after each invocation and calls driver.quit() to end the WebDriver session and close its browser windows.

The null check matters if setup can fail before the driver field is assigned. Use quit() to end the full session; close() closes a window and is not a substitute for quitting the session.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 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.

Fresh browser per test or one browser per class?

Approach When it runs Trade-off
Fresh driver with @BeforeEach/@AfterEach Before and after each test invocation Favors isolated browser state and straightforward cleanup, but repeats browser startup.
Shared driver with @BeforeAll/@AfterAll Once around the class’s tests Can reduce startup overhead, but requires deliberate resetting of cookies, windows, navigation, and mutable state. Tests can affect one another.

JUnit Jupiter’s default test-instance lifecycle creates a new test-class instance for each test method, but the browser session is an external resource and still needs explicit cleanup. Class-level @BeforeAll and @AfterAll methods are static by default. To make them non-static, use @TestInstance(TestInstance.Lifecycle.PER_CLASS); then one test object serves all methods, so mutable fields can leak state between tests. Prefer per-test browser ownership unless you have a clear reason and reset strategy for sharing.

Which JUnit annotations are useful for Selenium tests?

Annotation Scope or purpose Practical use
@Test Declares one test method Keep a user-visible behavior and its assertions together.
@BeforeEach / @AfterEach Run around each test invocation Create and quit a per-test WebDriver.
@BeforeAll / @AfterAll Run once around test methods in a class Use for class-wide setup or teardown; static unless the class uses per-class test-instance mode.
@ParameterizedTest Runs a test with multiple argument sets Exercise the same behavior with varied inputs.
@RepeatedTest Runs a test a requested number of times Useful for repetition, but repetition alone does not vary test data.
@DisplayName Sets a human-readable class or method name in reports Describe the behavior rather than implementation details.
@Nested Groups related tests in an inner test class Organize tests by feature or page area.
@Tag Labels tests for filtering Use a small, agreed vocabulary such as smoke or slow.
@Disabled Disables a test or class Include a reason and remove it when the issue is resolved.
@ExtendWith Registers a Jupiter extension Use for reusable framework integrations; a hand-written driver lifecycle does not need one.

How to test multiple values with @ParameterizedTest

A parameterized test runs the same test method with supplied arguments. @ValueSource is concise for one argument per invocation; @CsvSource can supply multiple values per row. Add the Jupiter params module to the build, aligned to the version of the other Jupiter artifacts. The following is a pattern, not a complete test: the submit flow and assertion must match your application.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • 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.
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

@ParameterizedTest
@ValueSource(strings = { "Selenium", "JUnit Jupiter" })
void acceptsText(String input) {
    driver.findElement(By.name("my-text")).sendKeys(input);
    // Complete the flow and assert the application-specific result.
}

With a per-test driver lifecycle, each parameter invocation receives its own setup and teardown. That keeps one input’s browser state from carrying into the next invocation.

JUnit 5 and JUnit 4 are not interchangeable

Use Jupiter imports consistently in a Jupiter test. Jupiter’s @Test is a different annotation from JUnit 4’s @Test and does not carry JUnit 4-style attributes. Mixing imports or relying on JUnit 4 annotation behavior can prevent tests from being discovered or produce confusing build errors. Consult the JUnit 5.12.0 User Guide for Jupiter’s annotation and lifecycle rules.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • 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
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Build and browser setup

Your project needs Selenium’s Java libraries and JUnit Jupiter. Parameterized tests additionally need junit-jupiter-params at a version aligned with the rest of Jupiter. Choose versions that are compatible with one another and verify the release documentation for the versions selected; dependency coordinates are not universal across projects.

The example constructs ChromeDriver. Browser and driver management behavior, along with browser compatibility, can vary by Selenium release and CI environment. Check the documentation for your chosen Selenium release and ensure the browser environment used by the build is supported. The example does not require a hard-coded browser executable path.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 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.

Troubleshooting Selenium tests with Jupiter

  • The test is not discovered: Check that the class uses Jupiter imports such as org.junit.jupiter.api.Test, and that the build includes compatible Jupiter test support. Do not accidentally import JUnit 4’s org.junit.Test.
  • The browser starts but remains open: Confirm that @AfterEach is imported from Jupiter and that driver.quit() runs. Keep the null guard when setup might fail before assigning the field.
  • A class-level lifecycle method is rejected: Make @BeforeAll or @AfterAll static, or explicitly opt into @TestInstance(TestInstance.Lifecycle.PER_CLASS) and account for shared object state.
  • An element lookup fails intermittently: The page may not have rendered the element when the lookup runs. Synchronize against the relevant condition with the wait approach chosen for your application instead of increasing delays indiscriminately.
  • Parameterized annotations or sources are unresolved: Add the Jupiter params module and align its version with the other Jupiter artifacts.
  • ChromeDriver cannot start in CI: Verify that the selected Selenium release, installed browser, and execution environment are compatible. Avoid assuming a local machine’s browser setup is available on the CI worker.

Or skip the browser setup

If you need a screenshot rather than an interactive browser test, ScreenshotNeo is a website screenshot API and MCP server. A single GET request captures a URL as an image or PDF. Its cleanup can accept cookie banners and remove known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server offers take_screenshot, get_page_info, and capture_pdf for AI agents and MCP clients.

cURL example, with the endpoint parameters documented in the ScreenshotNeo documentation:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

The free plan includes 1,000 screenshots per month with no card required; paid plans start at $5 for 3,000 shots. Sign up for ScreenshotNeo’s free plan.

Frequently Asked Questions

Does @AfterEach run after every parameterized test input?

Yes. Each parameterized-test invocation is a test invocation, so the per-invocation teardown runs after it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can I use @BeforeAll without a static method?

Yes, if the class opts into Jupiter’s per-class test-instance lifecycle with @TestInstance(TestInstance.Lifecycle.PER_CLASS).

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.