A CSV file and a method

A literal source is fine for values written in the test. When the cases come from a method or a file, the source changes but the test method does not: it still takes one parameter per argument, and each case is still one test. This lesson runs a method source and shows the file source next to it.

@MethodSource

@MethodSource("pairs") names a static method of the test class. The method returns a stream of arguments, and Jupiter calls the test once per element. The method may return a Stream, an Iterable or an array; a stream is the usual form because it reads like a list of cases.

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; public class SourceTest { static Stream<Arguments> pairs() { return Stream.of(Arguments.of(1, 2), Arguments.of(3, 4)); } @ParameterizedTest @MethodSource("pairs") void addsOne(int n, int next) { assertEquals(n + 1, next); } }

Arguments and a stream

Arguments.of(a, b) wraps the values of one case. Stream.of(...) makes the stream. The test method takes the values as separate parameters, in the order they were given to Arguments.of. A method with one parameter can return a stream of that type instead of Arguments.

The source method must be static when the test class uses the default lifecycle. It is allowed to compute the cases, read a constant list or build them from a helper; that is the reason to choose it over a literal source. The method is called once per test method that names it.

A CSV file on the class path

A file source reads the same rows as @CsvSource from a file. The file is found on the class path, which for this course means the output folder or the folder the launcher scans. The annotation is not a whole test file on its own; it replaces the literal source line:

@ParameterizedTest @CsvFileSource(resources = "/pairs.csv", numLinesToSkip = 1) void adds(int a, int b, int sum) { assertEquals(sum, a + b); }

The file must be copied into the class path before the run, which this course does not do for the checked example: the page runs the method source, and the file form is shown as the annotation it is. A project with Maven puts the file in src/test/resources and the build copies it; this image has no network and no build tool, so a page that needs a resource writes it next to the classes in the same checked folder.

The report

javac -Xlint:all -cp /opt/java-tools/junit-platform-console-standalone.jar -d out SourceTest.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 ✔
│  └─ SourceTest ✔
│     └─ addsOne(int, int) ✔
│        ├─ [1] 1, 2 ✔
│        └─ [2] 3, 4 ✔
└─ JUnit Vintage ✔

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

Which source to use

Use @ValueSource for one value per case, @CsvSource for a few rows of several values, @MethodSource when the cases are computed or come from code, and @CsvFileSource when the table is long enough to live outside the source. All four feed the same test method, so changing the source does not change the test body.

Exercises

  1. Add a third pair to the method source and run. How many tests does the report count?
  2. Change the method to return Stream.of(1, 2, 3) and the test to take one parameter. Does it compile?
  3. Rename the source method without renaming the annotation and read the error. What does the launcher say?
  4. Write the same two cases as a @CsvSource and compare the reports. Which line differs?

Questions

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

  1. What does the method named by @MethodSource return?

    Answer

    A stream of arguments, one element per case

    The source supplies one Arguments (or one value) per invocation.

  2. Why must the source method be static in the default lifecycle?

    Answer

    Jupiter calls it before it has a test instance

    With one instance per test, the source has no instance to belong to.

  3. Where does @CsvFileSource look for its file?

    Answer

    On the class path

    The resource is loaded from the class path, which is why a build copies it next to the classes.

  4. What does this program print? public class Q1 { public static void main(String[] args) { System.out.println(1 + 1); } }

    Answer

    2

    The addition gives 2, and println prints it.

  5. What does this program print? public class Q2 { public static void main(String[] args) { System.out.println(java.util.stream.Stream.of("a", "b").count()); } }

    Answer

    2

    The stream has two elements, and count returns 2.

  6. What does this program print? public class Q3 { public static void main(String[] args) { int[] values = {3, 4}; System.out.println(values[0] + values[1]); } }

    Answer

    7

    The two elements are added, and the sum is 7.

  7. What does this program print? public class Q4 { public static void main(String[] args) { String text = "pairs"; System.out.println(text.startsWith("pair")); } }

    Answer

    true

    pairs begins with pair, so startsWith is true.

  8. What is the difference between @CsvSource and @CsvFileSource?

    Answer

    The rows are written in the annotation or read from a file on the class path

    Both read CSV rows; only the place the rows live changes.

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

    Answer

    2

    Integer division of 4 by 2 is 2.

  10. A test method takes two parameters. What must each element of the method source be?

    Answer

    An Arguments with two values

    Arguments.of takes the values in the order of the parameters.

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