Parameterized tests
A parameterized test is one test method that JUnit runs many times, once per set of input values. You write the check once and supply a table of cases instead of copying the method.
Detailed Explanation
Some rules have edges rather than a single answer. A shipping discount might be zero below five items, ten percent from five to nine, and fifteen percent from ten upward. Testing that properly means six or seven cases, and writing six near-identical test methods means six places to update when the rule changes.
A parameterized test solves this. You annotate the method with @ParameterizedTest instead of @Test, declare the inputs as method parameters, and attach a source that supplies the values. JUnit then runs the method once per row and reports each row as a separate test in the results. One row failing does not hide the others.
This lives in a separate artifact, org.junit.jupiter:junit-jupiter-params. The umbrella junit-jupiter dependency pulls it in; a project that depends only on junit-jupiter-api will not compile the annotation.
The sources you will actually use:
@ValueSourcefor a single parameter of a simple type:strings,ints,longs,doubles,booleans,classes.@CsvSourcefor a small inline table of several parameters, one row per string. JUnit converts each column to the declared parameter type.@MethodSourcefor anything the annotation cannot express: objects, records, nulls, generated data. It points at a static method returningStream<Arguments>.@EnumSourceto run once per constant of an enum, withnamesandmodeto include or exclude specific ones.@CsvFileSourcewhen the table is large enough to deserve its own resource file.
Argument conversion is implicit and mostly does what you want. A @CsvSource column reading 5 binds to an int parameter, 2024-01-31 binds to a LocalDate, and PAID binds to an enum constant. An empty column becomes an empty string; use nullValues = "NULL" when you need a real null.
Name your cases. @ParameterizedTest(name = "{0} items gives {1} percent off") turns an unreadable "[3]" in the report into a sentence that tells you which row broke. The placeholders are zero-indexed parameter positions.
Reach for this when the behaviour is a table: validation rules, parsing formats, boundary values, currency rounding, state transitions. Reach for a plain @Test when each case needs different setup or asserts something different, because forcing those into one method produces a parameter list full of flags and a body full of if.
The cost is debuggability. When row four fails you cannot put a breakpoint on "row four" directly, and a @MethodSource that computes data can drift far enough from the assertion that the test stops explaining itself. Keep the data literal where you can, and resist generating hundreds of rows: a parameterized test still runs the whole body every row, so a slow body multiplies.
Code Examples
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
class DiscountTest {
static int discountPercent(int itemCount) {
if (itemCount >= 10) return 15;
if (itemCount >= 5) return 10;
return 0;
}
static boolean isValidCoupon(String code) {
return code != null && !code.isBlank();
}
// Six runs, six entries in the report. "name" makes each one readable.
@ParameterizedTest(name = "{0} items gives {1} percent off")
@CsvSource({
"1, 0", // below the first band
"4, 0", // last value before the band changes
"5, 10", // first value in the band
"9, 10",
"10, 15",
"50, 15"
})
void discountBands(int itemCount, int expectedPercent) {
assertEquals(expectedPercent, discountPercent(itemCount));
}
@ParameterizedTest
@ValueSource(strings = { " ", "\t", "\n" }) // whitespace-only codes
void blankCouponCodesAreRejected(String code) {
assertFalse(isValidCoupon(code));
}
}import static org.junit.jupiter.api.Assertions.assertEquals;
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 ShippingTest {
record Destination(String country, boolean express) {}
static int shippingCents(Destination to, int orderCents) {
if (orderCents >= 5_000 && !to.express()) return 0; // free standard shipping
return to.express() ? 1_500 : 499;
}
// @MethodSource is the escape hatch: it can supply real objects, not just literals.
// The method must be static under the default per-method test lifecycle.
static Stream<Arguments> shippingCases() {
return Stream.of(
Arguments.of(new Destination("US", false), 5_000, 0),
Arguments.of(new Destination("US", false), 4_999, 499),
Arguments.of(new Destination("US", true), 9_000, 1_500));
}
@ParameterizedTest(name = "{0} at {1} cents costs {2} cents to ship")
@MethodSource("shippingCases")
void shippingIsChargedPerDestination(Destination to, int orderCents, int expectedCents) {
assertEquals(expectedCents, shippingCents(to, orderCents));
}
}Common Gotchas
Missing `junit-jupiter-params` breaks compilation
`@ParameterizedTest` and the source annotations live in their own artifact. A project wired to `junit-jupiter-api` alone fails with "cannot find symbol" on the annotation import.
A non-static `@MethodSource` factory fails at runtime
under the default per-method lifecycle JUnit calls the factory before any instance exists. Make the method `static`, or annotate the class `@TestInstance(Lifecycle.PER_CLASS)`.
A `@MethodSource` that returns no arguments passes silently by default
an empty stream means zero runs and zero assertions, which looks like success. Set `@ParameterizedTest` alongside a non-empty source, or fail the build on empty sources explicitly.
`@CsvSource` splits on commas inside your data too
a column containing a comma needs single quotes around it, as in `"'Smith, Ana', 42"`, otherwise the row gains a column and the argument count stops matching.