October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober 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

How to Write Parameterized JUnit Tests for Selenium

Run one Selenium test flow against multiple inputs with JUnit Jupiter. Choose an argument source, configure dependencies, and ensure every browser session is closed.

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.

Use JUnit Jupiter’s @ParameterizedTest with an argument source such as @ValueSource, @CsvSource, or @MethodSource. JUnit runs the test method once for each supplied case; Selenium drives the browser within each invocation. Add junit-jupiter-params, ensure your build runs the Jupiter engine, and close every WebDriver session with quit().

How parameterized Selenium tests fit together

A parameterized test separates the test procedure from its input cases. JUnit Jupiter supplies arguments and creates a distinct invocation for each case; Selenium’s Java binding sends commands to the browser and lets the test inspect the result. A test method must use @ParameterizedTest and at least one argument source.

Pick a source based on the shape of your data: @ValueSource for one argument, @CsvSource for small rows with multiple arguments, or @MethodSource for richer or programmatically constructed cases. Give invocations useful display names so a failure report identifies the input that failed.

Set up JUnit Jupiter and Selenium

Maven dependencies

Include Selenium’s Java binding and JUnit Jupiter’s parameter support in the test project. This Maven fragment uses version properties rather than claiming a particular release is current; set them to versions supported by your project and Java runtime. Keep JUnit components aligned, for example through a consistent JUnit BOM strategy, and configure the build to run the Jupiter engine.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<properties>
  <junit.version>YOUR_JUNIT_VERSION</junit.version>
  <selenium.version>YOUR_SELENIUM_VERSION</selenium.version>
</properties>

<dependencies>
  <dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>${selenium.version}</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-params</artifactId>
    <version>${junit.version}</version>
    <scope>test</scope>
  </dependency>
</dependencies>

Check the official JUnit User Guide and Selenium install documentation for current setup guidance; sample dependency versions on install pages can change. If your build already manages JUnit versions or supplies the engine through another dependency, avoid introducing conflicting versions.

Browser and driver prerequisites

A local run needs a browser available in the execution environment. Current Selenium bindings include Selenium Manager, which can act as a fallback when you have not supplied a driver yourself; manually downloading a driver is therefore not mandatory in every setup. Consult the Selenium Manager documentation if driver resolution fails. For execution across browser and operating-system combinations, a Selenium Grid or hosted grid becomes relevant; it adds infrastructure and operational choices beyond a local test.

Write a compact CSV-driven test

This example runs the same search flow with two query/heading pairs. Replace the example URL, locators, and expected text with values from your application. The code is an illustrative pattern, not a claim that the placeholder site was tested.

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

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

class SearchFormTest {
    @ParameterizedTest(name = "search for {0} gives {1}")
    @CsvSource({
        "selenium, Selenium results",
        "junit, JUnit results"
    })
    void searchShowsExpectedHeading(String query, String expectedHeading) {
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://example.test/search");
            driver.findElement(By.name("q")).sendKeys(query);
            driver.findElement(By.cssSelector("button[type='submit']")).click();
            assertEquals(expectedHeading,
                driver.findElement(By.cssSelector("h1")).getText());
        } finally {
            driver.quit();
        }
    }
}

Each CSV row supplies arguments in order to the test method. The number and types of supplied values must match the method parameters. The test method cannot be private or static; check the JUnit ParameterizedTest API for current signature rules.

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

Choose an argument source that fits the cases

One input per invocation: @ValueSource

Use a value source when only one input varies. It is concise for lists such as search terms, usernames, or supported language codes.

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

@ParameterizedTest(name = "search accepts query {0}")
@ValueSource(strings = {"selenium", "junit"})
void searchAcceptsQuery(String query) {
    // Run the browser steps for this query and assert the result.
}

Small multi-column cases: @CsvSource

CSV is easy to scan when a short set of cases has the same columns, such as input plus expected output. Keep the columns in the same order as the method arguments and use a display name that makes the case identifiable in test output.

Rank #4
Sale

Richer or computed cases: @MethodSource

Use a method source when rows are numerous, need construction in Java, or do not fit neatly in inline CSV. A provider can return an Arguments stream, with one argument bundle per invocation:

import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class SearchCasesTest {
    static Stream<Arguments> searchCases() {
        return Stream.of(
            Arguments.of("selenium", "Selenium results"),
            Arguments.of("junit", "JUnit results")
        );
    }

    @ParameterizedTest(name = "search for {0} gives {1}")
    @MethodSource("searchCases")
    void searchShowsExpectedHeading(String query, String expectedHeading) {
        // Create a WebDriver, perform the search, assert, and always quit the driver.
    }
}

JUnit supports additional source return types and rules for provider visibility, conversions, and argument aggregation. Consult the JUnit guide’s parameterized-test section for those details rather than assuming a provider signature from an older example.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Manage WebDriver lifetime and test isolation

Per-invocation creation and cleanup

Creating a driver inside each invocation and calling quit() in a finally block keeps cleanup adjacent to session creation and still runs it when an assertion or browser command fails. If setup fails before the driver is created, adapt cleanup to handle that possibility, for example by initializing a nullable driver and checking it before quitting.

JUnit lifecycle hooks

For shared setup methods, use JUnit lifecycle hooks such as @BeforeEach and @AfterEach. Selenium’s Java example demonstrates this pattern, including a null check before quit(). Keep the lifecycle choice explicit: each parameterized invocation should have a deliberate session policy, and parallel invocations must not accidentally share mutable browser state.

Local execution or Grid

A local browser is a practical starting point. A Selenium Grid is useful when the suite needs execution across browser and operating-system combinations or distributed capacity. The choice trades local simplicity for broader execution options and additional setup; Selenium’s documentation discusses scaling across browser/OS combinations.

Troubleshoot common failures

  • JUnit does not recognize the test: confirm that Jupiter is configured in the build and that the test project includes junit-jupiter-params. Align JUnit component versions.
  • Parameterized test reports a missing source or invalid arguments: add an argument source and ensure each case supplies the expected number and compatible types of arguments. Verify the provider name and supported return type for @MethodSource.
  • The method signature is rejected: a parameterized test method cannot be private or static; check the applicable JUnit API and guide for provider rules.
  • Browser fails to start because a driver cannot be found: check that a supported browser is installed and available. Selenium Manager can resolve a missing driver as a fallback, but inspect its documentation and environment-specific errors if resolution fails.
  • Browser remains open after a failure: put driver.quit() in guaranteed cleanup such as finally or a teardown hook.
  • Intermittent failures when running in parallel: inspect whether invocations share a browser, account, test data, or application state. Isolate those resources or change the concurrency/lifecycle design.
  • A browser command cannot find the expected element: verify the application URL and locator against the current page, and check that the page has reached the state the test expects before interacting. The illustrative example’s selectors and expected text must be replaced with application-specific values.

Or skip the browser setup

If you need a screenshot rather than an interactive Selenium assertion, ScreenshotNeo can return an image or PDF through one GET request. It is not a replacement for a browser test that clicks controls and checks application behavior, but it can remove browser setup for capture workflows.

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

Quick Recap

SaleBestseller No. 3
SaleBestseller No. 4
Pragmatic Unit Testing in Java with JUnit
Pragmatic Unit Testing in Java with JUnit
Used Book in Good Condition
$13.55
SaleBestseller No. 5

cURL:

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

Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

See the ScreenshotNeo API documentation for request options. Cookie banners are accepted and removed before capture, along with known newsletter popups and chat widgets; these steps can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server lets AI agents use screenshot tools. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000.

Sign up for ScreenshotNeo’s free plan.

Further reading

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
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

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.