Parameterised tests with @ValueSource and @CsvSource
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's delivery rule has five cases. Five copy-pasted tests that differ in one number are noise, and the sixth case never gets written.
@ParameterizedTest with @ValueSource
@ParameterizedTest marks a test method that takes parameters, instead of @Test. A source annotation supplies the arguments, and JUnit runs the method once per argument set, reporting each run as its own test.
Several SKUs should all be valid, and several should all be rejected. Write each rule once and let JUnit run it for every value.
Example 1 · The rules under test, checked with a table in plain Java
import java.math.BigDecimal;
final class DeliveryCharge { // free delivery from Rs 499.00, otherwise Rs 40.00 static BigDecimal forSubtotal(BigDecimal subtotal) { return subtotal.compareTo(new BigDecimal("499.00")) >= 0 ? new BigDecimal("0.00") : new BigDecimal("40.00"); }}
final class SkuRules { // 3-20 characters: A-Z, 0-9 and '-' static boolean isValid(String sku) { return sku != null && sku.matches("[A-Z0-9-]{3,20}"); }}
public class TableDrivenDemo { public static void main(String[] args) { String[][] deliveryTable = { {"120.00", "40.00"}, {"498.99", "40.00"}, {"499.00", "0.00"}, {"17999.00", "0.00"}, }; for (String[] row : deliveryTable) { BigDecimal actual = DeliveryCharge.forSubtotal(new BigDecimal(row[0])); String result = actual.equals(new BigDecimal(row[1])) ? "PASS" : "FAIL"; System.out.println(result + " subtotal " + row[0] + " -> delivery " + row[1]); }
for (String sku : new String[] {"MOB-RN13", "BK-CLEAN", "kb 1", "AB"}) { System.out.println("sku " + sku + " valid: " + SkuRules.isValid(sku)); } }}PASS subtotal 120.00 -> delivery 40.00 PASS subtotal 498.99 -> delivery 40.00 PASS subtotal 499.00 -> delivery 0.00 PASS subtotal 17999.00 -> delivery 0.00 sku MOB-RN13 valid: true sku BK-CLEAN valid: true sku kb 1 valid: false sku AB valid: false
What this code does
- The delivery rule and the SKU rule are the classes the JUnit tests below check; in
shoplite-apithey are public classes incom.shoplite.cart. The loop overdeliveryTableis the idea behind parameterised tests: one check, many rows. - Done by hand, all rows share one result list and one failure stops nothing. JUnit's version adds a separate, named test result per row.
Example 2 · @ValueSource: valid and invalid SKUs
Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/cart)
package com.shoplite.cart;
import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.ValueSource;
class SkuRulesTest {
@ParameterizedTest @ValueSource(strings = {"MOB-RN13", "BK-CLEAN", "ACC-PB20K", "ABC"}) void acceptsWellFormedSkus(String sku) { assertTrue(SkuRules.isValid(sku)); }
@ParameterizedTest @ValueSource(strings = {"kb 1", "AB", "mob-rn13", "ABCDEFGHIJKLMNOPQRSTU"}) void rejectsBadSkus(String sku) { assertFalse(SkuRules.isValid(sku)); }}SkuRulesTest
acceptsWellFormedSkus(String)
[1] sku=MOB-RN13
[2] sku=BK-CLEAN
[3] sku=ACC-PB20K
[4] sku=ABC
rejectsBadSkus(String)
[1] sku=kb 1
[2] sku=AB
[3] sku=mob-rn13
[4] sku=ABCDEFGHIJKLMNOPQRSTU
[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.073 s -- in com.shoplite.cart.SkuRulesTestWhat this code does
- Two methods, eight test runs: each value becomes one run with its own name, shown here as the IDE's test tree. Surefire counts every run as a test.
- The bad SKUs each break a different part of the rule: a space, too short, lower case, 21 characters. Listing them in one place makes it easy to see which cases are covered.
The simplest source is @ValueSource: a list of literal values of one type, such as @ValueSource(strings = {"MOB-RN13", "BK-CLEAN"}) or @ValueSource(ints = {1, 5, 99}). Use it when every input should give the same outcome, such as "all of these SKUs are valid".
Fix the error
Fix the parameterised test
Read the error JUnit reports, then pick the line that fixes it.
The test method has a parameter, but JUnit cannot supply it.
Error
ParameterResolutionException: No ParameterResolver registered for parameter [java.lang.String sku] in method [void SkuRulesTest.acceptsWellFormedSkus(String)]
@CsvSource tables, and @CsvFileSource
@CsvSource is a source that takes rows of comma-separated values; each row fills the test method's parameters in order. It is ideal for tables of input and expected result, such as subtotal and delivery charge.
Delivery costs Rs 40 below a Rs 499 subtotal and is free from Rs 499. One table of rows checks every case, including both sides of the boundary.
Example 3 · @CsvSource and @CsvFileSource: delivery charge tables
Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/cart)
// ===== src/test/java/com/shoplite/cart/DeliveryChargeTest.java =====package com.shoplite.cart;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.CsvFileSource;import org.junit.jupiter.params.provider.CsvSource;
class DeliveryChargeTest {
@ParameterizedTest(name = "subtotal {0} -> delivery {1}") @CsvSource({ "0.00, 40.00", "120.00, 40.00", "498.99, 40.00", "499.00, 0.00", "17999.00, 0.00" }) void chargesDeliveryBelowRs499(BigDecimal subtotal, BigDecimal expected) { assertEquals(expected, DeliveryCharge.forSubtotal(subtotal)); }
@ParameterizedTest(name = "{0}: subtotal {1} -> delivery {2}") @CsvFileSource(resources = "/delivery-charges.csv", numLinesToSkip = 1) void chargesFromTheSharedTable(String caseName, BigDecimal subtotal, BigDecimal expected) { assertEquals(expected, DeliveryCharge.forSubtotal(subtotal)); }}// ===== src/test/resources/delivery-charges.csv =====case,subtotal,expected"small order, pens only",60.00,40.00just below free,498.99,40.00exactly free,499.00,0.00DeliveryChargeTest
chargesDeliveryBelowRs499(BigDecimal, BigDecimal)
subtotal 0.00 -> delivery 40.00
subtotal 120.00 -> delivery 40.00
subtotal 498.99 -> delivery 40.00
subtotal 499.00 -> delivery 0.00
subtotal 17999.00 -> delivery 0.00
chargesFromTheSharedTable(String, BigDecimal, BigDecimal)
small order, pens only: subtotal 60.00 -> delivery 40.00
just below free: subtotal 498.99 -> delivery 40.00
exactly free: subtotal 499.00 -> delivery 0.00
[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.081 s -- in com.shoplite.cart.DeliveryChargeTestWhat this code does
- Each CSV row fills
subtotalandexpectedin order, and JUnit converts the text toBigDecimal(keeping the two decimals, soassertEqualscompares correctly). Spaces around values are trimmed, so the columns can be lined up. - The file version reads the same kind of table from
src/test/resources, skips the header line, and the double quotes keepsmall order, pens onlyas one value despite its comma (a CSV file quotes with", while@CsvSourcequotes with'). Custom names put the case into every row of the report.
JUnit converts each text value to the parameter's type, including int, BigDecimal, enums and dates. Text with commas goes in single quotes, and an empty column is null.
@CsvFileSource(resources = "/delivery-charges.csv", numLinesToSkip = 1) reads the same kind of table from a file in src/test/resources, skipping the header line. Use it when the table is long or is shared with people who are not programmers.
@NullAndEmptySource and @EnumSource
@EnumSource is a source that runs the test once for each constant of an enum. names limits it to some constants, and mode = EnumSource.Mode.EXCLUDE runs all constants except the named ones.
Blank input and every order status are cases people forget. Two sources cover them without listing each value by hand.
Example 4 · @NullAndEmptySource and @EnumSource
Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/cart)
package com.shoplite.cart;
import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.EnumSource;import org.junit.jupiter.params.provider.NullAndEmptySource;import org.junit.jupiter.params.provider.ValueSource;
import com.shoplite.order.OrderStatus;
class MissingAndStatusTest {
@ParameterizedTest @NullAndEmptySource @ValueSource(strings = {" ", " "}) void missingOrBlankSkusAreInvalid(String sku) { assertFalse(SkuRules.isValid(sku)); }
@ParameterizedTest @EnumSource(value = OrderStatus.class, names = {"PLACED"}) void aPlacedOrderCanBeCancelled(OrderStatus status) { assertTrue(status.canBeCancelled()); }
@ParameterizedTest @EnumSource(value = OrderStatus.class, names = {"PLACED"}, mode = EnumSource.Mode.EXCLUDE) void noOtherStatusCanBeCancelled(OrderStatus status) { assertFalse(status.canBeCancelled()); }}MissingAndStatusTest
missingOrBlankSkusAreInvalid(String)
[1] sku=null
[2] sku=
[3] sku=
[4] sku=
aPlacedOrderCanBeCancelled(OrderStatus)
[1] status=PLACED
noOtherStatusCanBeCancelled(OrderStatus)
[1] status=SHIPPED
[2] status=DELIVERED
[3] status=CANCELLED
[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.066 s -- in com.shoplite.cart.MissingAndStatusTestWhat this code does
@NullAndEmptySourceaddsnulland""to the two blank strings from@ValueSource: four runs for every kind of "no SKU". This test assumesOrderStatushas a smallcanBeCancelled()method that returns true only forPLACED.EXCLUDEruns every status exceptPLACED. If someone adds aRETURNEDstatus later, it is tested automatically, and the test fails if it was wrongly made cancellable.
@NullAndEmptySource adds two extra runs to a String (or collection) parameter: one with null and one with "". Combine it with @ValueSource(strings = {" ", " "}) to cover blank input in one test. @NullSource and @EmptySource add just one of them.
With EXCLUDE, a status added later is tested automatically, so a new status cannot slip through untested.
Predict the output
How many runs?
Count the test runs that JUnit reports.
Round 1 of 2
One blank value, plus the null and empty runs.
@MethodSource for objects, and display names
Arguments.of(...) builds one row of arguments for a @MethodSource test: its values go to the test method's parameters in order, like Arguments.of(cart, expectedTotal).
A cart with items cannot be written as CSV text. A static method builds the carts, and @MethodSource feeds them to the test.
Example 5 · @MethodSource with ready-made carts
Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/cart)
package com.shoplite.cart;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;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;
class CartTotalCasesTest {
static Stream<Arguments> carts() { Cart empty = new Cart();
Cart books = new Cart(); books.add("BK-CLEAN", new BigDecimal("499.00"), 1); books.add("BK-PRAG", new BigDecimal("650.00"), 2);
Cart merged = new Cart(); merged.add("PEN-BLU", new BigDecimal("10.00"), 2); merged.add("PEN-BLU", new BigDecimal("10.00"), 3);
return Stream.of( Arguments.of("empty cart", empty, new BigDecimal("0.00")), Arguments.of("two books, three copies", books, new BigDecimal("1799.00")), Arguments.of("same pen added twice", merged, new BigDecimal("50.00"))); }
@ParameterizedTest(name = "[{index}] {0} -> Rs {2}") @MethodSource("carts") void totalAddsEveryLine(String description, Cart cart, BigDecimal expected) { assertEquals(expected, cart.total()); }}CartTotalCasesTest
totalAddsEveryLine(String, Cart, BigDecimal)
[1] empty cart -> Rs 0.00
[2] two books, three copies -> Rs 1799.00
[3] same pen added twice -> Rs 50.00
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.058 s -- in com.shoplite.cart.CartTotalCasesTestWhat this code does
- A
Cartwith items cannot be written as CSV text, so the static methodcarts()builds three ready carts and returns them with their expected totals asArguments. - The first argument is only a description used in the name pattern
{0};{2}is the expected total and{index}the row number. When a row fails, its name says which cart it was.
The source method returns a Stream<Arguments> (or a list), one Arguments.of(...) per row.
Each run gets a display name: by default its index and arguments, like [1] subtotal=120.00, expected=40.00. @ParameterizedTest(name = "{0} -> delivery {1}") sets your own pattern: {0}, {1} are the arguments by position, {arguments} is all of them, {index} is the run number. A good name makes a failing row obvious in the report.
Find the bug
Find the mismatch
Tap the line where the table and the method disagree.
JUnit cannot find the source of the arguments.
Round 1 of 2The junit-jupiter-params artifact
junit-jupiter-params is the JUnit artifact (package org.junit.jupiter.params) that provides @ParameterizedTest and the sources. The junit-jupiter dependency already includes it.
Parameterised tests need one artifact on the test classpath.
<!-- Only needed when the pom lists junit-jupiter-api and -engine separately --><dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-params</artifactId> <version>5.14.4</version> <scope>test</scope></dependency>In shoplite-api the Spring Boot test starter brings it, so usually there is nothing to add. Only a project that lists junit-jupiter-api and junit-jupiter-engine separately needs it as a third test dependency.
Next step
Check your understanding
10 quick questions