Many cases with parameterized tests
25 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Writing eight nearly identical @Test methods that only differ in their input numbers and expected result creates noisy duplicate code. Parameterized tests in JUnit 5 let you write one test method and feed it an entire table of inputs and expected outputs.
@ParameterizedTest and @CsvSource: your test table in code
In JUnit 5 (org.junit.jupiter.params.*), a parameterized test replaces @Test with @ParameterizedTest and adds a data source annotation such as @CsvSource. Each string inside @CsvSource({...}) is one comma-separated row of arguments passed to the test method parameters in order.
Example 1 · Running a @ParameterizedTest with @CsvSource across normal and boundary rows
import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method;
// In an IDE with JUnit 5 (junit-jupiter-params) on the classpath, you import:// import org.junit.jupiter.params.ParameterizedTest;// import org.junit.jupiter.params.provider.CsvSource;// import static org.junit.jupiter.api.Assertions.assertEquals;public class ParameterizedCsvDemo { @Retention(RetentionPolicy.RUNTIME) @interface ParameterizedTest { String name() default "[{index}] {arguments}"; }
@Retention(RetentionPolicy.RUNTIME) @interface CsvSource { String[] value(); }
static void assertEquals(boolean expected, boolean actual) { if (expected != actual) { throw new AssertionError("expected: <" + expected + "> but was: <" + actual + ">"); } }
// Method under test: leap year rule in the Gregorian calendar static boolean isLeapYear(int year) { if (year % 400 == 0) return true; if (year % 100 == 0) return false; return year % 4 == 0; }
@ParameterizedTest(name = "[{index}] year={0} -> leap={1}") @CsvSource({ "2024, true", "2023, false", "1900, false", "2000, true" }) void leapYearTable(int year, boolean expected) { assertEquals(expected, isLeapYear(year)); }
public static void main(String[] args) throws Exception { Method m = ParameterizedCsvDemo.class.getDeclaredMethod("leapYearTable", int.class, boolean.class); ParameterizedTest pt = m.getAnnotation(ParameterizedTest.class); CsvSource csv = m.getAnnotation(CsvSource.class); int index = 1; for (String row : csv.value()) { String[] parts = row.split(",\\s*"); int year = Integer.parseInt(parts[0]); boolean expected = Boolean.parseBoolean(parts[1]); m.invoke(new ParameterizedCsvDemo(), year, expected); String display = pt.name() .replace("{index}", String.valueOf(index++)) .replace("{0}", parts[0]) .replace("{1}", parts[1]); System.out.println("PASS " + display); } }}PASS [1] year=2024 -> leap=true PASS [2] year=2023 -> leap=false PASS [3] year=1900 -> leap=false PASS [4] year=2000 -> leap=true
What this code does
- All four cases — ordinary multiple of 4 (
2024), odd year (2023), century non-leap year (1900), and 400-year leap year (2000) — sit in one compact@CsvSourcetable. - The
name = "[{index}] year={0} -> leap={1}"template turns each row into a clear, self-documenting line in the test runner.
Example 2 · Each row in a parameterized test runs independently even when an earlier row fails
public class RowIndependenceDemo { // Buggy palindrome check: case-sensitive (fails on mixed case) static boolean buggyIsPalindrome(String s) { int l = 0, r = s.length() - 1; while (l < r) { if (s.charAt(l++) != s.charAt(r--)) return false; } return true; }
public static void main(String[] args) { String[][] csvRows = { {"Normal odd palindrome", "radar", "true"}, {"Mixed case palindrome", "RaceCar", "true"}, {"Non-palindrome", "java", "false"}, {"Empty string", "", "true"} };
int passed = 0, failed = 0; for (int i = 0; i < csvRows.length; i++) { String label = csvRows[i][0]; String input = csvRows[i][1]; boolean expected = Boolean.parseBoolean(csvRows[i][2]); boolean actual = buggyIsPalindrome(input); if (actual == expected) { passed++; System.out.println("PASS [" + (i + 1) + "] " + label); } else { failed++; System.out.println("FAIL [" + (i + 1) + "] " + label + " -> expected: <" + expected + "> but was: <" + actual + ">"); } } System.out.println("Summary: " + passed + " passed, " + failed + " failed"); }}PASS [1] Normal odd palindrome FAIL [2] Mixed case palindrome -> expected: <true> but was: <false> PASS [3] Non-palindrome PASS [4] Empty string Summary: 3 passed, 1 failed
What this code does
- If all four assertions were inside one plain
@Testmethod, row 2's failure would abort the method before rows 3 and 4 ever ran. - With a parameterized table, row 2 fails with a clear message while rows 3 and 4 still execute and report
PASS.
- Replace
@Testwith@ParameterizedTest(never put both annotations on the same method unless you want an extra no-arg run to fail). - List comma-separated rows inside
@CsvSource({ "input1, expected1", "input2, expected2" }). - JUnit converts CSV text columns into
int,long,double,boolean, orStringmethod parameters automatically.
For example, if your method signature is void checksshipping(int orderTotal, boolean expected) and your @CsvSource row is "50, true", JUnit automatically parses "50" as int 50 and "true" as boolean true and runs the method once for that row. Unlike putting a loop of assertions inside a single @Test method (which stops at the first failure), JUnit runs every row of @CsvSource as a separate test invocation. If row 3 fails, rows 4, 5, and 6 still run and report their own pass/fail status.
Naming test cases clearly with name placeholders
By default JUnit labels each table row as [1] 50, true. A name pattern in @ParameterizedTest makes each row describe itself. The code below gives every row a readable name.
@ParameterizedTest(name = "[{index}] {0}: year={1} -> leap={2}")@CsvSource({ "'Divisible by 4', 2024, true", "'Century, not by 400', 1900, false", "'Divisible by 400', 2000, true"})void leapYearWithReason(String reason, int year, boolean expected) { assertEquals(expected, isLeapYear(year));}Notice that in @CsvSource, single quotes '...' wrap string values that contain spaces or commas, and '' (two single quotes) represents an empty string "".
By default, JUnit displays each row in the test runner tree as [1] 50, true, [2] 49, false, and so on. When a test table has ten rows, you can make the report even clearer in two ways:
- Custom display pattern: Pass
name = "[{index}] total={0} -> freeShipping={1}"inside@ParameterizedTest(name = ...). Here{index}is the 1-based row number,{0}is the first parameter,{1}is the second parameter, and{arguments}is the full comma-separated list. - A
reasoncolumn in@CsvSource: Include a human-readable label as the first CSV column (for example,"'Exact lower boundary', 50, true") and usename = "[{index}] {0}". - Use
{index}in@ParameterizedTest(name = ...)for the 1-based invocation number. - Use
{0},{1},{2}to insert the method's parameter values into the test runner label. - Wrap strings containing spaces in single quotes inside
@CsvSource, and write''for an empty string"".
Covering normal, boundary, and edge cases in one table
A @CsvSource table is the test table from Lesson 1 written as code, so a reviewer sees which cases are covered. The code below mixes normal, boundary and edge rows.
When you need to pass arrays or complex objects that do not fit neatly in CSV strings, JUnit 5 also provides @MethodSource, which points to a static method returning Stream<Arguments>. For numbers, booleans, and strings, @CsvSource is the cleanest choice.
Example 3 · Putting a reason column and edge cases (including empty string) in one table
import java.util.Objects;
public class EdgeCaseTableDemo { // Counts vowels (a, e, i, o, u, case-insensitive) in s static int countVowels(String s) { int count = 0; for (int i = 0; i < s.length(); i++) { char c = Character.toLowerCase(s.charAt(i)); if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { count++; } } return count; }
static void runRow(int index, String reason, String input, int expected) { int actual = countVowels(input); if (!Objects.equals(expected, actual)) { throw new AssertionError("expected: <" + expected + "> but was: <" + actual + ">"); } System.out.println("PASS [" + index + "] " + reason + " | input='" + input + "' -> " + actual); }
public static void main(String[] args) { // Equivalent to @CsvSource with a reason column and '' for empty string: runRow(1, "Normal lowercase word", "mentor", 2); runRow(2, "Empty string boundary", "", 0); runRow(3, "No vowels at all", "rhythm", 0); runRow(4, "All uppercase vowels", "AEIOU", 5); runRow(5, "Single consonant", "z", 0); }}PASS [1] Normal lowercase word | input='mentor' -> 2 PASS [2] Empty string boundary | input='' -> 0 PASS [3] No vowels at all | input='rhythm' -> 0 PASS [4] All uppercase vowels | input='AEIOU' -> 5 PASS [5] Single consonant | input='z' -> 0
What this code does
- Adding a
reasoncolumn ("Normal lowercase word","Empty string boundary","All uppercase vowels") documents why each row exists right inside the test report. - If a future refactor removes
Character.toLowerCase, row[4] All uppercase vowelsfails immediately while rows[1],[2],[3], and[5]still pass.
A @CsvSource block is the exact code version of the test table you learned to build in Lesson 1. Grouping normal cases, boundary endpoints, and structural edge cases into one @CsvSource table lets any reviewer see at a glance what cases are covered and what might be missing.
@CsvSource, an unquoted empty column is parsed as null, whereas '' (two single quotes) is parsed as an empty String ("").Next step
Check your understanding
10 quick questions