JUnit 5 Parameterized Tests: A Complete Tutorial

JUnit 5 Parameterized Tests: A Complete Tutorial

Parameterized tests let you run the same test logic with different inputs without duplicating code. JUnit 5 ships with a rich parameterized test API that covers simple value lists, CSV rows, factory methods, enum values, and custom argument providers.

Setup

Add the JUnit 5 dependency (includes junit-jupiter-params):

Maven:

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.11.0</version>
    <scope>test</scope>
</dependency>

Gradle (Kotlin DSL):

testImplementation("org.junit.jupiter:junit-jupiter:5.11.0")

tasks.test {
    useJUnitPlatform()
}

@ValueSource — Single Argument Lists

The simplest source. Supports int, long, double, float, byte, short, char, boolean, String, and Class:

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

class EmailValidatorTest {

    @ParameterizedTest
    @ValueSource(strings = {"user@example.com", "admin@company.org", "test+tag@mail.co"})
    void acceptsValidEmail(String email) {
        assertTrue(EmailValidator.isValid(email));
    }

    @ParameterizedTest
    @ValueSource(strings = {"", " ", "not-an-email", "@missing.com"})
    void rejectsInvalidEmail(String input) {
        assertFalse(EmailValidator.isValid(input));
    }

    @ParameterizedTest
    @ValueSource(ints = {1, 10, 100, Integer.MAX_VALUE})
    void acceptsPositiveAmounts(int amount) {
        assertTrue(Account.isValidAmount(amount));
    }
}

Testing null and empty with @NullSource and @EmptySource

@ParameterizedTest
@NullSource
void rejectsNull(String input) {
    assertThrows(NullPointerException.class, () -> EmailValidator.isValid(input));
}

@ParameterizedTest
@EmptySource
void rejectsEmpty(String input) {
    assertFalse(EmailValidator.isValid(input));
}

// Combined: null, empty, and blank strings
@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = {" ", "\t", "\n"})
void rejectsBlankOrNull(String input) {
    assertFalse(EmailValidator.isValid(input));
}

@EnumSource — Enum Values

enum Status { PENDING, ACTIVE, SUSPENDED, DELETED }

@ParameterizedTest
@EnumSource(Status.class)
void statusHasDisplayName(Status status) {
    assertNotNull(status.getDisplayName());
}

// Only specific values
@ParameterizedTest
@EnumSource(value = Status.class, names = {"PENDING", "ACTIVE"})
void activeStatusesCanLogin(Status status) {
    assertTrue(authService.canLogin(status));
}

// Exclude specific values
@ParameterizedTest
@EnumSource(value = Status.class, names = {"DELETED"}, mode = EnumSource.Mode.EXCLUDE)
void nonDeletedStatusesAppearInSearch(Status status) {
    assertTrue(searchService.isIndexed(status));
}

@CsvSource — Multiple Arguments

Use @CsvSource when each test case needs multiple arguments:

@ParameterizedTest
@CsvSource({
    "USD, 100, $100.00",
    "EUR, 250, €250.00",
    "GBP, 0, £0.00"
})
void formatsAmount(String currency, int amount, String expected) {
    assertEquals(expected, formatter.format(currency, amount));
}

Handling special characters

Use single quotes for string literals containing commas:

@CsvSource({
    "'Smith, John', 25",
    "'Doe, Jane', 30"
})
void parsesName(String fullName, int age) { ... }

Null values in CSV

An empty field in @CsvSource becomes null for object types:

@CsvSource({
    "Alice, 30",
    "Bob,",       // age will be null (Integer)
    ", 25"        // name will be null
})
void handlesNulls(String name, Integer age) { ... }

@CsvFileSource — Arguments from a File

For large datasets, put arguments in a CSV file under src/test/resources:

# src/test/resources/test-cases/currencies.csv
currency,amount,expected
USD,100,$100.00
EUR,250,€250.00
GBP,0,£0.00
@ParameterizedTest
@CsvFileSource(resources = "/test-cases/currencies.csv", numLinesToSkip = 1)
void formatsAmountFromFile(String currency, int amount, String expected) {
    assertEquals(expected, formatter.format(currency, amount));
}

@MethodSource — Factory Methods

@MethodSource delegates argument generation to a static factory method that returns a Stream, List, Iterable, or array:

class OrderValidatorTest {

    @ParameterizedTest
    @MethodSource("validOrders")
    void acceptsValidOrder(Order order) {
        assertTrue(validator.isValid(order));
    }

    static Stream<Order> validOrders() {
        return Stream.of(
            new Order("item-1", 1, "USD"),
            new Order("item-2", 10, "EUR"),
            new Order("bundle-3", 5, "GBP")
        );
    }
}

Multiple arguments from @MethodSource

Return Stream<Arguments> for multi-argument cases:

@ParameterizedTest
@MethodSource("conversionData")
void convertsAmount(double amount, String from, String to, double expected) {
    assertEquals(expected, converter.convert(amount, from, to), 0.001);
}

static Stream<Arguments> conversionData() {
    return Stream.of(
        Arguments.of(100.0, "USD", "EUR", 92.0),
        Arguments.of(100.0, "EUR", "GBP", 86.0),
        Arguments.of(1.0,   "GBP", "USD", 1.27)
    );
}

Referencing methods in other classes

@ParameterizedTest
@MethodSource("com.example.TestData#currencyCodes")
void acceptsCurrencyCode(String code) {
    assertTrue(validator.isValidCurrency(code));
}

@ArgumentsSource — Custom Providers

For reusable, complex argument generation, implement ArgumentsProvider:

class RandomOrderProvider implements ArgumentsProvider {

    @Override
    public Stream<? extends Arguments> provideArguments(ExtensionContext ctx) {
        Random rng = new Random(42);
        return IntStream.range(0, 20)
            .mapToObj(i -> Arguments.of(
                "item-" + rng.nextInt(1000),
                rng.nextInt(99) + 1,
                List.of("USD", "EUR", "GBP").get(rng.nextInt(3))
            ));
    }
}

@ParameterizedTest
@ArgumentsSource(RandomOrderProvider.class)
void handlesRandomOrders(String itemId, int qty, String currency) {
    assertNotNull(service.create(itemId, qty, currency));
}

Custom Display Names

By default, JUnit 5 generates display names like [1] value1, value2. Customize them with name:

@ParameterizedTest(name = "{index}: {0} + {1} = {2}")
@CsvSource({
    "1, 1, 2",
    "5, 3, 8",
    "10, -3, 7"
})
void adds(int a, int b, int expected) {
    assertEquals(expected, a + b);
}

Placeholders:

  • {index} — 1-based invocation index
  • {0}, {1}, ... — argument values
  • {arguments} — comma-separated list of all arguments
  • {displayName} — display name of the method

Argument Conversion

JUnit 5 automatically converts strings to primitive types, enums, UUID, File, Path, URI, URL, Locale, and more. For custom types, implement ArgumentConverter or TypedArgumentConverter:

class CurrencyConverter extends TypedArgumentConverter<String, Currency> {

    protected CurrencyConverter() {
        super(String.class, Currency.class);
    }

    @Override
    protected Currency convert(String source) {
        return Currency.getInstance(source);
    }
}

@ParameterizedTest
@ValueSource(strings = {"USD", "EUR", "GBP"})
void acceptsCurrency(@ConvertWith(CurrencyConverter.class) Currency currency) {
    assertNotNull(currency.getDisplayName());
}

Aggregating Arguments with @AggregateWith

When arguments don't map 1:1 to parameters, use ArgumentsAggregator:

class OrderAggregator implements ArgumentsAggregator {
    @Override
    public Order aggregateArguments(ArgumentsAccessor accessor, ParameterContext ctx) {
        return new Order(
            accessor.getString(0),
            accessor.getInteger(1),
            accessor.getString(2)
        );
    }
}

@ParameterizedTest
@CsvSource({
    "item-1, 3, USD",
    "item-2, 7, EUR"
})
void processesOrder(@AggregateWith(OrderAggregator.class) Order order) {
    assertTrue(processor.process(order));
}

Combining Parameterized Tests with @Nested

class PricingTest {

    @Nested
    class FreeUsers {
        @ParameterizedTest
        @ValueSource(ints = {1, 5, 9})
        void canRunFewerThanTenTests(int count) {
            assertTrue(pricing.canRun(Plan.FREE, count));
        }

        @ParameterizedTest
        @ValueSource(ints = {10, 50, 100})
        void blockedAboveTenTests(int count) {
            assertFalse(pricing.canRun(Plan.FREE, count));
        }
    }

    @Nested
    class ProUsers {
        @ParameterizedTest
        @ValueSource(ints = {1, 100, 10000})
        void canRunAnyNumberOfTests(int count) {
            assertTrue(pricing.canRun(Plan.PRO, count));
        }
    }
}

Running Specific Invocations

In IntelliJ or the CLI, you can run a single parameterized invocation by its index. With Maven:

mvn test -Dtest="OrderTest#processesOrder[2]"

Complete Example

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.*;
import static org.junit.jupiter.api.Assertions.*;

class DiscountCalculatorTest {

    private final DiscountCalculator calc = new DiscountCalculator();

    @ParameterizedTest(name = "{0}% off ${1} = ${2}")
    @CsvSource({
        "10, 100, 90.0",
        "25, 200, 150.0",
        "50, 80,  40.0",
        "100, 50, 0.0"
    })
    void appliesDiscount(int percent, double original, double expected) {
        assertEquals(expected, calc.apply(percent, original), 0.001);
    }

    @ParameterizedTest
    @ValueSource(ints = {-1, 101, 200})
    void rejectsInvalidDiscountPercent(int percent) {
        assertThrows(IllegalArgumentException.class,
            () -> calc.apply(percent, 100.0));
    }

    @ParameterizedTest
    @NullAndEmptySource
    void rejectsBlankCouponCode(String code) {
        assertThrows(IllegalArgumentException.class,
            () -> calc.applyCode(code, 100.0));
    }

    @ParameterizedTest
    @MethodSource("premiumCodes")
    void acceptsPremiumCode(String code, double expectedRate) {
        assertEquals(expectedRate, calc.rateForCode(code), 0.001);
    }

    static Stream<Arguments> premiumCodes() {
        return Stream.of(
            Arguments.of("PREMIUM10", 0.10),
            Arguments.of("PREMIUM25", 0.25),
            Arguments.of("VIP50",     0.50)
        );
    }
}

Quick Reference

Source Best for
@ValueSource Single values of one type
@NullSource, @EmptySource, @NullAndEmptySource Null/empty edge cases
@EnumSource Enum values, with optional filtering
@CsvSource Multi-argument inline test data
@CsvFileSource Multi-argument data in a CSV file
@MethodSource Complex objects, factory logic
@ArgumentsSource Reusable external argument providers

Testing Parameterized Behavior End-to-End

Unit-level parameterized tests validate one function at a time. For testing the full user-visible behavior — "does this validation surface the right error to the user in the browser?" — HelpMeTest runs end-to-end tests written in plain English using Robot Framework and Playwright, with no source code access required.

The two layers complement each other: JUnit 5 parameterized tests cover every edge case at the unit level, HelpMeTest covers the user experience paths that matter most.

Read more

Start now free