Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 119 ยท Testing

Parameterized Tests

Run one JUnit test against many inputs with @ParameterizedTest, @ValueSource, @CsvSource, @MethodSource and @EnumSource, plus @RepeatedTest and dynamic tests.

Many behaviors are best checked with a table of examples: "0 kg costs 4.99, 2 kg costs 4.99, 2.5 kg costs 7.99, 20 kg costs 24.99". Writing a separate test method for each row means copying the same three lines over and over, and when the method signature changes you update a dozen copies.

A parameterized test is one test method that JUnit runs once per row of input, reporting each run as its own test. You write the logic once and list the data next to it. This lesson covers the @ParameterizedTest family and its argument sources, readable display names, argument conversion, parameterized classes, @RepeatedTest and fully dynamic tests built at runtime with @TestFactory. It assumes you know the basics from Unit Testing with JUnit 6 and Test Lifecycle and Organization.

Your first parameterized test

Replace @Test with @ParameterizedTest, add a source annotation that supplies the values, and give the method a parameter to receive each one. The simplest source is @ValueSource, which takes one array of literals: strings, ints, longs, doubles, chars, booleans, classes and a few more.

The annotations live in the junit-jupiter-params module (package org.junit.jupiter.params). The junit-jupiter dependency from the previous lessons already includes it.

Java @ValueSource and null/empty sources

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The report shows each method as a group with one line per value: [1] "ada", [2] "grace_h" and so on. If one value fails, only that invocation goes red, and the others still run. That is the big win over a loop inside a single @Test, which stops at the first bad value and hides the rest.

@NullSource, @EmptySource and the combined @NullAndEmptySource add null and an empty value (empty string, empty list, empty array) to any other source, because @ValueSource cannot contain null. Edge cases like these are where most validation bugs live, so make them a habit.

Choosing an argument source

Source Supplies Good for
@ValueSource one literal per invocation a list of single inputs
@NullSource, @EmptySource, @NullAndEmptySource null and/or an empty value edge cases, combined with another source
@CsvSource rows of comma-separated values, inline input/expected tables
@CsvFileSource rows from a CSV file on the classpath large tables maintained outside the code
@EnumSource constants of an enum "works for every status" checks
@MethodSource whatever a static factory method returns objects, lists, computed data
@FieldSource the contents of a static field fixed data sets shared between tests
@ArgumentsSource a custom ArgumentsProvider class reusable, complex generators

Tables with @CsvSource

@CsvSource is the workhorse. Each string is one row; JUnit splits it on commas and passes the columns to the method's parameters in order. With a text block (textBlock = """ ... """) the table looks like a table, and lines starting with # are comments.

Columns arrive as strings and JUnit converts them to the parameter types: numbers, boolean, char, enums (by constant name), BigDecimal, LocalDate (2026-03-01), Duration (PT15M), File, URI, UUID, Currency and more. Any class with a single-String factory method or constructor works too.

Java Shipping rates as a CSV table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A few CSV rules are worth memorizing:

  • Single quotes delimit a value that contains commas or leading/trailing spaces: 'no, comma'. Unquoted values are trimmed.
  • '' is an empty string, while a completely empty column (a,,c) is null. Use nullValues = "N/A" to treat a marker as null too.
  • useHeadersInDisplayName = true treats the first row as column names and uses them in the report: [1] input = " padded ", trimmed = "padded".
  • Use delimiter = '|' when commas are part of your data, and keep each table small enough to read at a glance.
  • Note that 2.01 was needed to test the step from 4.99 to 7.99. The rows that matter most sit right on boundaries: just below, on and just above each threshold.

Tables in files: @CsvFileSource

For a large table, keep it in src/test/resources and load it from the classpath:

Java
@ParameterizedTest
@CsvFileSource(resources = "/shipping-rates.csv", numLinesToSkip = 1)
void matchesPublishedRateTable(double kilograms, Zone zone, BigDecimal expected) {
    assertEquals(expected, Shipping.cost(kilograms, zone));
}

numLinesToSkip = 1 skips the header row (or use useHeadersInDisplayName = true). The same quoting rules apply, with double quotes instead of single ones.

Objects and computed data: @MethodSource

CSV can only express values that convert from strings. When a test needs real objects (a list, a record, a mock), point @MethodSource at a static method that returns a Stream, Iterable, array or List of arguments:

  • If the test has one parameter, the method can return the values directly, such as Stream<String>.
  • For several parameters, return Stream<Arguments> and build each row with Arguments.of(a, b, c) (or the static import arguments(...)).
  • Arguments.argumentSet("name", a, b) gives a row a name that appears in the report instead of its raw values, which helps when the values print badly.
  • @MethodSource with no value looks for a factory with the same name as the test. A factory in another class is referenced as "com.shop.TestData#orders".

@FieldSource (JUnit 5.11 and later) is the same idea for a static field: @FieldSource("CURRENCIES") reads a List or array field.

Java @MethodSource, @FieldSource and @EnumSource

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The two @EnumSource tests split the enum in two with names and mode = EXCLUDE. That pattern has a nice property: if someone adds a new status like RETURNED, it automatically lands in cannotCancelAfterwards, so the new constant is tested on day one. Plain @EnumSource (with no attributes) uses every constant of the parameter's enum type, and mode = MATCH_ANY with regex names selects by pattern.

Display names

The name attribute of @ParameterizedTest controls how each invocation is labeled. Placeholders:

Placeholder Becomes
the invocation number, starting at 1
, , ... one argument by position
all arguments, comma-separated
name = value pairs using parameter names (needs the -parameters compiler flag; otherwise arg0, arg1)
the name given with Arguments.argumentSet
the method's display name

The default is "[{index}] {argumentSetNameOrArgumentsWithNames}", which is what you saw in the first example. A good custom name reads as a sentence, like "{0} kg to {1} costs {2}", so a failing row explains itself in the CI log.

JUnit 6 puts quotes around text arguments in display names, so "" and " " stay distinguishable from each other. Because every @CsvSource column starts out as text, the shipping test would print "0.5" kg to "DOMESTIC" costs "4.99"; that is why it sets quoteTextArguments = false, which gives the cleaner 0.5 kg to DOMESTIC costs 4.99. Keep the quotes on for tests where blank or padded strings matter.

Converting and aggregating arguments

When the built-in conversion is not enough, you have three tools:

  • @ConvertWith(MyConverter.class) on a parameter runs your ArgumentConverter, for example to turn "3x150" into a Line.
  • ArgumentsAccessor as the only parameter gives you the raw row: accessor.getString(0), accessor.getInteger(1), accessor.get(2, LocalDate.class).
  • @AggregateWith(LineAggregator.class) builds one object from several columns, so the test method takes a Line instead of three loose values.
Java
@ParameterizedTest
@CsvSource({"pen, 3, 150", "pad, 1, 400"})
void lineFromColumns(ArgumentsAccessor row) {
    var line = new Line(row.getString(0), row.getInteger(1), row.getLong(2));
    assertTrue(line.quantity() > 0);
}

Parameters supplied by sources must come first in the method signature; any parameters JUnit injects itself, such as TestInfo, go after them.

Parameterizing a whole class

Sometimes every test in a class should run against several configurations: each currency, each storage implementation, each locale. JUnit 6 offers @ParameterizedClass for that. The class gets a source annotation, and the values arrive through a constructor (a record works nicely) or through fields marked @Parameter. Every test in the class then runs once per value, grouped in the report.

Java
@ParameterizedClass
@ValueSource(strings = {"USD", "EUR", "JPY"})
class MoneyFormatTest {
    @Parameter
    String currency;

    @Test
    void formatsZero() { ... }

    @Test
    void formatsNegativeAmounts() { ... }
}

@ParameterizedClass arrived in JUnit 5.13 and is still marked experimental, so its details may change. The older alternative, an abstract test class with one small subclass per configuration, works in every version.

Running the same test repeatedly: @RepeatedTest

@RepeatedTest(n) runs a test n times with no different input. It is useful when the code itself varies between runs: random number generation, hashing, concurrency. Inject RepetitionInfo to know which repetition you are in, and set failureThreshold to stop after a number of failures instead of drowning in identical reports.

Tests built at runtime: @TestFactory

Every source above is fixed when the class is compiled. A test factory goes further: a method annotated @TestFactory returns a Stream (or Collection) of DynamicTest objects that you build at runtime, each with a display name and an executable. DynamicContainer groups them, so you can generate whole trees, for example one container per data file and one test per line.

The example combines both features: a repeated test that checks a random password generator, and a factory that turns a small text specification into dynamic tests grouped by section.

Java @RepeatedTest and @TestFactory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Lifecycle methods do not run per dynamic test. @BeforeEach and @AfterEach run once around the whole @TestFactory method, not around each DynamicTest it returns. If each dynamic test needs fresh state, create it inside the test's lambda.

Prefer @ParameterizedTest when the inputs are known in advance; it is easier to read and tools understand it better (you can rerun one invocation from the IDE). Reach for @TestFactory when the tests really are data: generated from files, from a directory listing or from another system's specification.

Pitfalls

  • Don't compute the expected value with the code under test. assertEquals(Shipping.cost(w, z), Shipping.cost(w, z)) proves nothing. Expected values should be literal facts you worked out by hand.
  • Don't put branches in the test body. If the method says if (expectedError) assertThrows(...) else assertEquals(...), split it into two parameterized tests: one for valid inputs, one for invalid ones.
  • Keep rows meaningful. Ten rows that exercise the same path add run time, not confidence. Choose boundaries, edge cases and one or two typical values.
  • Watch the report size. A @MethodSource that generates 10,000 rows creates 10,000 test results. For that scale, a property-based testing library (such as jqwik, which runs on the JUnit Platform) is a better fit.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A @ParameterizedTest has @ValueSource(ints = {1, 2, 3}) and the value 2 fails. What does the report show?

    Each value is a separate invocation with its own result, so one bad value does not hide the others.
  2. 2. In @CsvSource("apple,,'', pear"), what are the second and third values?

    An empty, unquoted column becomes null, while '' (two single quotes) is an explicit empty string.
  3. 3. Which source should you use to pass a List of records to a parameterized test?

    @MethodSource calls a static factory method that can return any objects, including lists and records, wrapped in Arguments when there are several parameters.
  4. 4. A @TestFactory returns five DynamicTests and the class has a @BeforeEach method. How many times does @BeforeEach run?

    Lifecycle callbacks wrap the @TestFactory method, not the individual dynamic tests it produces.
  5. 5. Why is @EnumSource(mode = EXCLUDE, names = {"NEW", "PAID"}) a good choice for "cannot cancel" tests?

    EXCLUDE runs every constant except the listed ones, so a new status is covered without anyone remembering to add it.

Summary

  • @ParameterizedTest + a source runs one method many times; every invocation is reported separately, so one bad row does not hide the rest.
  • @ValueSource for single literals; @NullAndEmptySource for edge cases; @CsvSource (with textBlock) and @CsvFileSource for input/expected tables; @EnumSource for enum constants; @MethodSource and @FieldSource for objects.
  • CSV values convert automatically to numbers, enums, BigDecimal, LocalDate and more. '' is an empty string; an empty column is null.
  • Name invocations with name = "{0} kg to {1} costs {2}" or Arguments.argumentSet(...) so failures explain themselves.
  • @ParameterizedClass (experimental) runs a whole class per value; @RepeatedTest repeats a test with no new input; @TestFactory builds DynamicTests at runtime, but lifecycle methods wrap only the factory.

Next: Test Doubles and Mockito, where you test code that depends on databases, payment gateways and clocks without calling the real thing.