One method, many values

Five even numbers deserve five tests, but five methods that differ only in a literal are noise. A parameterised test is one method with a source of arguments: Jupiter calls it once per value and reports every call as its own test. This lesson uses the simplest source, @ValueSource, for integers and strings. The article Parameterised tests is the short version.

A parameterised test

The method is marked @ParameterizedTest instead of @Test, it takes the value as a parameter, and a second annotation names where the values come from. Jupiter runs the body once for every value and gives each run its own line in the report.

import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; public class EvenTest { @ParameterizedTest @ValueSource(ints = {2, 4, 6}) void even(int n) { assertTrue(n % 2 == 0); } @ParameterizedTest @ValueSource(strings = {"Ada", "Grace"}) void hasLetters(String name) { assertTrue(name.length() > 0); } }

@ValueSource

The annotation has one array per type: ints, longs, doubles, strings, booleans, chars and classes. A test method takes one parameter of that type, and the values are written in the annotation. It is the source for a short list of literals, not for a table of several columns; the next lessons cover the sources that take more.

A string source cannot hold null; use @NullSource, which lesson 019 covers. An empty string is allowed and is worth a case of its own when the method treats it differently.

Each invocation is a test

The counts table follows the invocations, not the methods. Three integers and two strings make five tests, and the tree shows the method once with a branch of cases under it. A failure in one case does not stop the other cases of the same method by default.

The display name of a case

By default a case is named [1] 2: the index and the value. The name attribute of the source changes it: @ValueSource(ints = {2, 4, 6}) with @ParameterizedTest(name = "even {0}") prints even 2. The placeholders are the arguments, and {displayName} is the default name.

A named case is easier to find in a report of a hundred cases, and the name goes into the failure line. Keep it short: the value is already there, and the sentence is for the person scanning the tree.

The report

javac -Xlint:all -cp /opt/java-tools/junit-platform-console-standalone.jar -d out EvenTest.java
junit execute --class-path out --scan-classpath --disable-ansi-colors

Thanks for using JUnit! Support its development at https://junit.org/sponsoring

╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│  └─ EvenTest ✔
│     ├─ even(int) ✔
│     │  ├─ [1] 2 ✔
│     │  ├─ [2] 4 ✔
│     │  └─ [3] 6 ✔
│     └─ hasLetters(String) ✔
│        ├─ [1] Ada ✔
│        └─ [2] Grace ✔
└─ JUnit Vintage ✔

Test run finished after 1169 ms
[         6 containers found      ]
[         0 containers skipped    ]
[         6 containers started    ]
[         0 containers aborted    ]
[         6 containers successful ]
[         0 containers failed     ]
[         5 tests found           ]
[         0 tests skipped         ]
[         5 tests started         ]
[         0 tests aborted         ]
[         5 tests successful      ]
[         0 tests failed          ]

The tree has two methods and five leaves. The containers are six because each parameterised method is a container of its invocations; the tests are five because each invocation is a test. The parameter types are part of the method line, which distinguishes two parameterised methods with the same name.

Exercises

  1. Add an odd number to the int source and run. Which case fails, and what does the tree line say?
  2. Add the empty string to the string source. Does hasLetters still pass?
  3. Set @ParameterizedTest(name = "even {0}") and run. Which lines of the tree change?
  4. Use @ValueSource(booleans = {true, false}) for a new method and predict the counts before you run.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. How many tests does a method with three int values and two string values report?

    Answer

    5, one per invocation

    Every invocation is a test, so three plus two makes five.

  2. Which annotation supplies the values in this lesson?

    Answer

    @ValueSource

    ValueSource holds one array of literals of a single type.

  3. What does the default display name of a case look like?

    Answer

    [1] 2

    The default is the index in brackets, a space and the value.

  4. What does this program print? public class Q1 { public static void main(String[] args) { int n = 6; System.out.println(n % 2 == 0); } }

    Answer

    true

    Six is even, so the remainder is 0 and the comparison is true.

  5. What does this program print? public class Q2 { public static void main(String[] args) { System.out.println("Ada".length()); } }

    Answer

    3

    Ada has three characters.

  6. What does this program print? public class Q3 { public static void main(String[] args) { int total = 0; for (int n : new int[] {2, 4, 6}) { total += n; } System.out.println(total); } }

    Answer

    12

    The loop adds 2, 4 and 6, so the total is 12.

  7. What does this program print? public class Q4 { public static void main(String[] args) { String text = "Grace"; System.out.println(text.substring(0, 1)); } }

    Answer

    G

    The substring starts at 0 and stops before 1, so it is G.

  8. Can @ValueSource(strings = {...}) supply a null?

    Answer

    No; use @NullSource for a null argument

    ValueSource holds literals; the null source is a separate annotation.

  9. What does one failing invocation do to the others?

    Answer

    The other invocations still run by default

    Each invocation is its own test, and Jupiter continues with the rest.

  10. What does this program print? public class Q5 { public static void main(String[] args) { boolean[] values = {true, false}; System.out.println(values.length); } }

    Answer

    2

    The array has two elements, so length is 2.

The code on this page was built with OpenJDK 21.0.13 (javac) and run with JUnit Platform Console Launcher 1.14.3 on Alpine Linux in a Docker container.

Article author: Arthur Isaev