Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 29 ยท JUnit advanced

Parameterized and Dynamic Tests

Run one JUnit test with many inputs using @ParameterizedTest, @CsvSource, @MethodSource and @EnumSource, then generate tests at runtime with @TestFactory.

Look at a test class for a price calculator and you will often see the same test written five times, with only the numbers changed. That is a lot of noise, and when the rule changes you must edit every copy. A parameterized test solves this: you write the test body once, list the inputs and expected results separately, and JUnit runs the body once per row and reports each row as its own test.

A dynamic test goes one step further. Instead of fixing the list of tests when you compile, a factory method builds the tests while the program runs, for example one test per file in a folder or per row in a table. This lesson covers both, using the real JUnit 6 library. If you need a refresher on @Test and assertions, see Your First JUnit Test and JUnit Assertions in Depth.

One body, many rows

Test body Written once, takes parameters.
Arguments A source supplies the rows.
Invocations Each row is reported separately.

A failing row never hides the other rows.

1 / 3

The setup: the module you need

Parameterized tests live in the junit-jupiter-params module. If you depend on the aggregate junit-jupiter artifact (as shown in earlier lessons), it is already there. The annotations are in org.junit.jupiter.params and org.junit.jupiter.params.provider. The examples below run on the real library: only the small runner at the bottom of each file stands in for Maven, Gradle or your IDE.

A parameterized method uses @ParameterizedTest instead of @Test, plus exactly one source annotation (or several, which are combined). The method parameters receive the values.

@ValueSource, @NullAndEmptySource and display names

@ValueSource supplies one literal per invocation: strings, ints, longs, doubles, booleans and a few other primitive types. It is perfect for "this property must hold for every one of these values". @NullAndEmptySource adds null and "" (and empty collections or arrays for those parameter types), which are the two inputs developers forget most often.

By default each invocation is named [1] value. The name attribute makes reports readable: is the 1-based position, , are the arguments, and is the method's own name.

@CsvSource: several arguments per row

@CsvSource takes one string per row, with values separated by commas. JUnit converts each text value to the parameter type (int, LocalDate, an enum, and so on). Use single quotes for values with commas or spaces, and write nothing between two commas for null. If you have many rows, @CsvFileSource(resources = "/prices.csv", numLinesToSkip = 1) reads them from a file on the test classpath instead.

Java @ValueSource and @CsvSource with real JUnit

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 twelve green lines (the three palindromes, four shipping rows, two non-palindromes and three blank inputs). Notice how the name pattern turns a bare row into a sentence you can read in a CI log. Each row is an independent test: if the third shipping row fails, rows one, two and four still run and still appear in the report.

@MethodSource: any objects you can build

Text-based sources cannot express everything. For objects, lists, records or computed data, point @MethodSource at a static factory method (or use the same name as the test method to skip the argument). It returns a Stream<Arguments>, an Iterable, or for single-parameter tests simply a Stream of the values. Arguments.of(...) bundles one row. If the factory lives in another class, write "com.shop.Fixtures#validOrders".

@EnumSource

@EnumSource(Level.class) runs the test once for every constant. Narrow it with names = {...}, or with mode = EXCLUDE, MATCH_ALL and a regex. It is the right tool for "the rule must work for every type we support", and it automatically covers constants added later, which a hand-written list would miss.

Argument conversion

JUnit converts text to many types implicitly: numbers, boolean, char, enums, LocalDate, Duration, UUID, Path and more, using each type's standard parser. When you need your own type, write an ArgumentConverter and attach it with @ConvertWith on the parameter. When a row has more values than you want in the signature, ArgumentsAccessor gives indexed access, and @AggregateWith builds one object from the whole row.

Java @MethodSource, @EnumSource and converters

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 last test fails on purpose: its second row expects 7 but gets 6. Read how the report names it: the name pattern puts the actual numbers in the line, and the other rows are untouched.

Dynamic tests with @TestFactory

A method annotated with @TestFactory does not run assertions itself. It returns tests: a Stream, Collection, Iterable or Iterator of DynamicTest (or DynamicContainer to nest them). Each DynamicTest.dynamicTest(name, executable) pairs a display name with a lambda that may throw.

Use dynamic tests when the set of cases is only known at run time, such as one test per fixture file, per row loaded from a database table, or one test per rule in a configuration. Two details trip people up:

  • Lifecycle callbacks do not wrap each dynamic test. @BeforeEach and @AfterEach run once around the whole factory method, not around each generated test. If the generated tests need a fresh object each, create it inside each lambda.
  • Dynamic tests cannot be filtered by IDE "run this method" in every tool and have no stable method to jump to, so prefer @ParameterizedTest when plain rows are enough.
Java @TestFactory generating tests at run time

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.

Count the lines: three tests from the first factory, three squares plus the lone test from the second, and the ordinary @Test. The generated names exist only because the code ran: no source line says "limit of slug is 40".

Choosing between them

  • Same logic, different data, known now: @ParameterizedTest.
  • The list of cases comes from the environment, or you need nested groups: @TestFactory.
  • Different logic per case: write separate @Test methods. A table of inputs forced into one parameterized test with if statements inside is a smell.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How is a parameterized method different from a normal test method in its annotations?

    @ParameterizedTest replaces @Test. Without a source annotation such as @ValueSource or @CsvSource, JUnit has no arguments and reports a configuration error.
  2. 2. One row of a @CsvSource test fails. What does JUnit do with the other rows?

    Every row is a separate invocation with its own result, so one failure never hides the others.
  3. 3. Where can a @MethodSource factory method normally live, and what must it be?

    By default the factory must be static because JUnit calls it before it creates a test instance. It returns a Stream, Iterable or similar of arguments.
  4. 4. Your @TestFactory returns five DynamicTests and the class has @BeforeEach. How many times does @BeforeEach run for the factory?

    Lifecycle callbacks wrap the factory method, not each generated test. Create per-test objects inside each lambda if you need a fresh one.

Summary

  • @ParameterizedTest replaces @Test; the body is written once and runs per row, each row reported on its own.
  • Sources: @ValueSource (one literal), @CsvSource / @CsvFileSource (several values as text), @MethodSource (any objects), @EnumSource (enum constants), plus @NullAndEmptySource.
  • Use the name attribute (, , ) to make reports readable.
  • JUnit converts text to many types implicitly; @ConvertWith and @AggregateWith handle your own types.
  • @TestFactory returns DynamicTest and DynamicContainer objects built at run time; @BeforeEach runs once per factory, not per generated test.

Next: Writing JUnit Extensions.