Skip to content
javahacks.dev
JUnit

JUnit 5 Parameterized Tests With ValueSource and Beyond

Write parameterized tests in JUnit 5 with ParameterizedTest, ValueSource, NullSource, EnumSource and a display name, and know when a table is clearer.

5 min read
Summarize in AI
Flat illustration of a test report with one failing test, with the JUnit5, GitHub Actions, Selenium, Jenkins and OpenJDK logos.

A parameterized test runs one test method several times with different arguments, and reports each run as its own test. It replaces the copy-pasted test methods that differ only in an input and an expected value, and it makes the list of cases visible in one place. This post covers the setup, the argument sources that need no code beyond an annotation, naming of the runs, conversion of arguments, and the line between a parameterized test and a test that should be two tests. It applies to JUnit 5 and 6.

Dependency

Parameterized tests live in a separate artifact from the core API. If you only depend on junit-jupiter-api, the annotation does not compile.

pom.xmlXML
<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter-params</artifactId>
  <version>${junit.version}</version>
  <scope>test</scope>
</dependency>

The aggregate artifact junit-jupiter brings the API, the params module and the engine, and spring-boot-starter-test includes it. If the tests do not run at all after you add them, check that the engine is present and that Surefire is recent enough; the usual causes are in JUnit 5 tests not running under Maven.

The first parameterized test

src/test/java/com/example/text/BlankCheckTest.javajava
class BlankCheckTest {

    @ParameterizedTest(name = "\"{0}\" is blank")
    @ValueSource(strings = {"", " ", "   ", "\t", "\n"})
    void detects_blank_strings(String input) {
        assertTrue(Strings.isBlank(input));
    }
}

@ParameterizedTest replaces @Test. @ValueSource supplies one argument per run, and the method receives it as a parameter. Each run appears in the report as a separate test, so a failure on the tab input is visible without reading the others. Without a name, the report shows [1] followed by the arguments, which is accurate and unfriendly; the {0} placeholder inserts the first argument, {index} the run number and {displayName} the method's own display name. Naming rules are in display names.

@ValueSource takes arrays of one type: strings, ints, longs, doubles, chars, booleans, classes and a few others. It supplies exactly one argument per run, which fits simple input checks. For two or more parameters, use @CsvSource or @MethodSource, described in argument sources.

Null and empty

Edge cases are where input bugs live, and two annotations cover them without writing the values:

java
@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = {" ", "\t"})
void rejects_blank_codes(String code) {
    assertThrows(IllegalArgumentException.class, () -> Codes.parse(code));
}

@NullSource, @EmptySource and the combination @NullAndEmptySource add null and "" (and empty collections or arrays for those parameter types) to the runs. Combine them with a @ValueSource for the blank strings, as above. The test now covers null, empty, and whitespace with four lines.

Enums

java
@ParameterizedTest
@EnumSource(value = OrderStatus.class, names = {"SHIPPED", "DELIVERED"})
void shipped_orders_cannot_be_cancelled(OrderStatus status) {
    assertFalse(new Order(status).canCancel());
}

@ParameterizedTest
@EnumSource(value = OrderStatus.class, mode = EnumSource.Mode.EXCLUDE, names = "NEW")
void only_new_orders_can_be_edited(OrderStatus status) { /* ... */ }

Without names, every constant runs, so adding a constant to the enum adds a run, and the test fails if the new status violates the rule. That is the strength of this source: it keeps tests honest as the code grows. Use mode = EXCLUDE to say "everything except", which is safer than listing the cases you remember. MATCH_ALL and MATCH_ANY take regular expressions.

Conversion

JUnit converts string arguments to the parameter type without code. A @ValueSource(strings = {"2026-03-01"}) feeding a LocalDate parameter is parsed using ISO format, and the same works for int, Duration, UUID, Path, enums and many more. For other formats, annotate the parameter with @JavaTimeConversionPattern("dd/MM/yyyy"), or write an ArgumentConverter and attach it with @ConvertWith. Implicit conversion keeps tests short, and an unparseable value fails the run with a clear conversion error, which is still a test failure and not a setup problem.

What not to parameterize

Parameterization is for the same behaviour on different data. It is the wrong tool in four cases.

When the cases need different assertions. A table where one row expects an exception and the next expects a value forces a branch in the test, and a branch in a test is a place for a bug. Write two tests.

When the setup differs. If half the runs need a mock configured one way and half another, the shared body hides what each case is about.

When there are two cases. A parameterized test with two rows is a more elaborate way to write two test methods and is harder to read.

When the data is the logic. If you compute the expected value in the test with the same formula as the code under test, the test cannot fail for a wrong formula. Write the expected values as literals, taken from the specification or from a hand calculation.

Keep the number of arguments small. Beyond three or four, the rows become unreadable, and a record or a named Arguments factory gives them labels.

Reading failures

When a run fails, the report shows its name, the arguments and the assertion message, and the other runs continue. The invocation index in the name lets you re-run a single case from the IDE. If the arguments are objects without a useful toString(), the names are unhelpful, so give the records a readable toString or use Arguments.argumentSet("expired token", token) to label a case. Each run goes through the full lifecycle, so @BeforeEach and @AfterEach run per invocation, as in lifecycle annotations; a heavy setup repeated per row is a reason to move to a class-level fixture.

Tag slow parameterized suites so they can be filtered, see JUnit tags. The broader tour of the framework is in the JUnit 5 handbook.

Combining sources and keeping the output tidy

Several source annotations can sit on one method, and JUnit concatenates their arguments in order. That is how @NullAndEmptySource plus @ValueSource works above. It means you can start with the obvious values and add a regression case from a bug report as one more line, which keeps the history of why each case exists in the diff. Add a short comment on the line that came from a ticket.

A parameterized test with five hundred runs is a different animal from a unit test: it floods the report and slows the build. If you find yourself generating a large grid of inputs, consider a property-based approach with jqwik, which generates cases and shrinks failures, and keep the JUnit parameterized tests for the handful of cases a reader should see.

When a table is clearer

For tests with many columns, a CSV or a method source reads better than a long @ValueSource. For tests that really are a table of inputs and outputs, such as a tax calculator, keep the table in a @CsvFileSource resource that a domain expert can review. The annotation reference is in the ParameterizedTest Javadoc and the full feature in the user guide.

Also inTesting
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.