JUnit MethodSource CsvSource and ArgumentsSource Usage
Feed multi parameter tests in JUnit with MethodSource, CsvSource, CsvFileSource and ArgumentsSource, and choose the one that keeps test data readable.

A parameterized test with a single argument is easy. The moment a test needs two or three inputs and an expected result, the choice of source annotation decides whether the test data is readable. JUnit offers several, and each one fits a different shape of data: @CsvSource for a small table of text and numbers, @CsvFileSource for a larger one in a file, @MethodSource for objects and computed values, and @ArgumentsSource for a provider class several tests share. This post shows each with an example, explains the conversion and naming details that cause surprises, and ends with a rule for choosing. It applies to JUnit 5 and 6; the simpler sources are in parameterized tests.
CsvSource: a table in the annotation
@ParameterizedTest(name = "{0} items cost {1} each -> {2}")
@CsvSource({
"1, 10.00, 10.00",
"5, 10.00, 47.50",
"10, 10.00, 90.00",
"10, 0.00, 0.00"
})
void applies_a_volume_discount(int quantity, BigDecimal price, BigDecimal expected) {
assertEquals(0, expected.compareTo(Discounts.total(quantity, price)));
}Each string is a row, and each comma-separated value becomes the next method parameter, converted to its type: int, BigDecimal, LocalDate, Duration, enums and many more by implicit conversion. Whitespace around values is trimmed. The table sits next to the assertion, so a reader sees input and expected output in one glance, and adding a case is one line. That is the strength: use it whenever the data fits on a line.
Several details cause trouble. A value containing a comma must be quoted with single quotes: "'Smith, Ann', 42". An empty value is null, while '' is an empty string, and @CsvSource(nullValues = "NIL") lets you write NIL for null. The delimiter can be changed with delimiter = '|', which helps when values contain commas. useHeadersInDisplayNames = true with a text block turns the header row into labels in the report. Text blocks work nicely for wide tables:
@CsvSource(useHeadersInDisplayNames = true, delimiter = '|', textBlock = """
quantity | price | expected
1 | 10.00 | 10.00
5 | 10.00 | 47.50
""")Compare BigDecimal with compareTo, as above, because equals also compares scale and 47.5 is not equal to 47.50.
CsvFileSource: a table in a file
When the table has dozens of rows, move it to a resource:
@ParameterizedTest
@CsvFileSource(resources = "/pricing/discounts.csv", numLinesToSkip = 1)
void matches_the_published_price_list(int quantity, BigDecimal price, BigDecimal expected) { /* ... */ }The file lives in src/test/resources, is read through the classpath, and has the same quoting rules. numLinesToSkip = 1 skips the header. A file suits data that a non-programmer maintains, such as a tax table from the finance team, or a list exported from a spreadsheet. The downside is distance: the reader must open another file to see the cases. Name the file for the behaviour, not the test. Reading files from the classpath, not by relative path, is explained in TempDir and test resources.
MethodSource: arguments from code
Text cannot express objects, collections or computed values. A factory method can:
static Stream<Arguments> orders() {
return Stream.of(
Arguments.of("empty cart", new Cart(List.of()), Money.ZERO),
Arguments.of("one item", new Cart(List.of(item("lamp", "24.90"))), Money.of("24.90")),
Arguments.of("two items", new Cart(List.of(item("lamp", "24.90"), item("bulb", "3.10"))), Money.of("28.00")));
}
@ParameterizedTest(name = "{0}")
@MethodSource("orders")
void totals_the_cart(String label, Cart cart, Money expected) {
assertEquals(expected, cart.total());
}The factory is static (unless the class uses @TestInstance(PER_CLASS)), returns a Stream, Iterable or array, and each Arguments.of(...) is one invocation. The first argument as a label, used in the name with {0}, is a habit worth adopting: objects have unreadable toString output, and a label makes the report legible. From JUnit 5.11, Arguments.argumentSet("empty cart", new Cart(...), Money.ZERO) attaches the label itself. A method in another class is referenced by its fully qualified name: @MethodSource("com.example.TestData#orders"). Generating arguments by code lets you build combinations with streams, but beware of cleverness: a test whose cases are produced by a nested loop is hard to read when it fails.
ArgumentsSource: a reusable provider
When several test classes need the same data, put it in a class:
class InvalidEmails implements ArgumentsProvider {
@Override
public Stream<? extends Arguments> provideArguments(ParameterDeclarations parameters, ExtensionContext context) {
return Stream.of("", "no-at-sign", "a@", "@b.com", "a [email protected]").map(Arguments::of);
}
}
@ParameterizedTest
@ArgumentsSource(InvalidEmails.class)
void rejects_invalid_email(String email) { assertFalse(Validators.isEmail(email)); }A provider can take part in the extension model: it gets the context, and it can read an annotation placed on the test through AnnotationBasedArgumentsProvider, which is how custom source annotations such as @InvalidEmails are built. The provideArguments signature changed in JUnit 5.13 and 6 to include ParameterDeclarations; the older one-parameter form is deprecated, so check the Javadoc for your version. Use a provider when the data has a domain meaning shared across tests, such as "all supported currencies" built from the enum or a database of fixtures.
Conversion rules worth knowing
Implicit conversion handles the common types, and it can surprise you. A value like 1 bound to a long parameter works; bound to a Long it works; bound to an Object it arrives as a String. An enum parameter takes the constant's name, case-sensitively. A LocalDate takes ISO format. For a custom type, annotate the parameter with @ConvertWith, which names an ArgumentConverter, or give the type a static valueOf(String) or a single-string constructor, and JUnit uses it. An ArgumentsAccessor parameter receives the whole row, which is useful for rows with many columns, and an ArgumentsAggregator builds a record from several columns, which keeps the test signature short when a row has seven fields.
Mismatched counts are reported as clear errors: more columns than parameters fails the run, while fewer is accepted if the extra parameters are resolved by other extensions, such as TestInfo. A test method can mix source arguments first with injected parameters after them, and the injected ones must come last.
Choosing
Use @CsvSource first. It is the most readable for inputs and outputs that are numbers and short strings. Move to @CsvFileSource when the table outgrows a screen or is maintained outside the code. Use @MethodSource when any value is an object or must be computed, or when you want labels. Use @ArgumentsSource for data reused by several classes. The same guidance applies to naming: {0} placeholders and the labels from display names keep failures readable, and assertion messages complete the picture, see readable assertions.
Keep the data honest
Write the expected values by hand, from the specification, not by running the code and pasting its output. A table generated from the implementation records the implementation's bugs as correct behaviour. Include the boundary rows: zero, one, the edge of each range, and the case that triggered the last bug. Keep each row independent, with no reliance on the previous row, because JUnit does not guarantee the order of invocations to anything beyond the order of the source. If a table needs a comment per row to explain it, the rows are probably separate tests.
Where this does not apply
If each case needs different setup or a different assertion, write separate tests. Property-based libraries such as jqwik generate cases from rules and shrink failures, and fit parsers and serialisers better than any table. The reference pages are the source annotations in the user guide and the Arguments Javadoc.


