Sub topic 9
Running One Test with Many Inputs
Often you want to check the same behavior with many different values. Does add work with small numbers? With negative numbers? With zero? You could write a separate test method for each case. That gets long and repetitive fast. JUnit gives you a better tool: the parameterized test.
A parameterized test is a single test method that JUnit runs many times, once for each set of input values you give it. A parameter is a value passed into a method. Here, JUnit passes the values into your test method for you.
Why Not Just Copy the Test?
Here is what repetition looks like without parameterized tests:
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class CalculatorRepeatedTest {
private final Calculator calculator = new Calculator();
@Test
void addOneAndOne() {
assertEquals(2, calculator.add(1, 1));
}
@Test
void addTwoAndThree() {
assertEquals(5, calculator.add(2, 3));
}
@Test
void addNegativeAndPositive() {
assertEquals(0, calculator.add(-4, 4));
}
}All three methods do the same thing. Only the numbers change. If you later rename add, you must fix three places. A parameterized test keeps the logic in one place and moves the numbers into a list.
Where Parameterized Tests Come From
Parameterized tests live in a module called junit-jupiter-params. A module is a separate piece of a library that you can include or leave out. If you added the junit-jupiter dependency from the setup chapter, you already have it. That one dependency bundles the API, the params module, and the test engine.
The annotations you need are in the package org.junit.jupiter.params.
Your First Parameterized Test with @CsvSource
Here is the repeated test from above, rewritten:
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class CalculatorParameterizedTest {
private final Calculator calculator = new Calculator();
@ParameterizedTest
@CsvSource({
"1, 1, 2",
"2, 3, 5",
"-4, 4, 0"
})
void addHandlesManyInputs(int a, int b, int expected) {
assertEquals(expected, calculator.add(a, b));
}
}Two annotations do the work:
@ParameterizedTestreplaces@Test. It tells JUnit this method runs once per set of inputs. Do not put both@Testand@ParameterizedTeston the same method.@CsvSourceis an argument source. An argument source is an annotation that supplies the input values. CSV means "comma-separated values". Each string is one row. Each comma splits the row into columns.
JUnit matches the columns to the method parameters in order. The first column goes to a, the second to b, and the third to expected. The text "-4" is turned into the int value -4 for you. This step is called type conversion.
Each row is its own test run. If row 2 fails, rows 1 and 3 still run, and the report shows exactly which row broke. You get that benefit without writing three methods.
Giving Each Run a Readable Name
By default, the IDE shows each run with names like [1] 1, 1, 2. You can choose a clearer name with the name attribute:
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class CalculatorNamedTest {
private final Calculator calculator = new Calculator();
@ParameterizedTest(name = "{0} + {1} = {2}")
@CsvSource({
"1, 1, 2",
"2, 3, 5"
})
void add(int a, int b, int expected) {
assertEquals(expected, calculator.add(a, b));
}
}{0} is replaced by the first argument, {1} by the second, and so on. The runs now appear as 1 + 1 = 2 and 2 + 3 = 5. You can also use {index} for the run number.
Other Argument Sources
@CsvSource is the most flexible source, but JUnit offers several others. Pick the one that fits your data.
| Source | What it supplies | Good for |
|---|---|---|
| `@ValueSource` | One value per run, from a single list | Testing one input at a time |
| `@CsvSource` | Several values per run, written inline | Input plus expected output |
| `@NullSource` | A single `null` | Checking null handling |
| `@EmptySource` | An empty string, list, or array | Checking empty input |
| `@NullAndEmptySource` | Both `null` and empty | Both checks in one line |
| `@EnumSource` | Each constant of an enum | Covering every enum value |
| `@MethodSource` | Values returned by a method you write | Complex objects or computed data |
@ValueSource for One Value per Run
Use @ValueSource when each run needs only one input. This test checks that several strings are not blank:
import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
class ValueSourceTest {
@ParameterizedTest
@ValueSource(strings = {"milk", "bread", "eggs"})
void itemNamesAreNotBlank(String item) {
assertFalse(item.isBlank());
}
}@ValueSource supports strings, ints, longs, doubles, booleans, chars, and a few other basic types. It does not support null. That is what the next sources are for.
Testing null and Empty Input
Code often breaks on null or empty input. These sources make it easy to cover those cases:
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.ValueSource;
class BlankInputTest {
static boolean isMissing(String text) {
return text == null || text.isBlank();
}
@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = {" ", "\t"})
void missingTextIsDetected(String text) {
assertTrue(isMissing(text));
}
}You can stack sources on one method. This test runs four times: with null, with "", with two spaces, and with a tab.
@MethodSource for Complex Data
Sometimes the inputs are objects, or you want to build them with code. @MethodSource points to a factory method. A factory method is a method whose job is to create and return values. It must be static and return a stream of Arguments:
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;
class DivideMethodSourceTest {
private final Calculator calculator = new Calculator();
static Stream<Arguments> divisionCases() {
return Stream.of(
Arguments.of(10, 2, 5),
Arguments.of(9, 3, 3),
Arguments.of(7, 2, 3)
);
}
@ParameterizedTest
@MethodSource("divisionCases")
void divideReturnsWholeNumberResult(int a, int b, int expected) {
assertEquals(expected, calculator.divide(a, b));
}
}The string "divisionCases" must match the method name exactly. Note the case 7, 2, 3. Java integer division drops the remainder, so 7 / 2 is 3. Parameterized tests are a good place to write down surprising cases like this one.
Common Mistakes and Edge Cases
Watch for these other traps:
- Commas inside values. A comma always splits columns. To keep a comma in a value, wrap the value in single quotes:
"'Smith, Jane', 30". - Empty versus null in CSV. An empty quoted value
''becomes an empty string. A completely empty column, as in"apple, ", becomesnull. This only works for object types likeString. Anintparameter cannot holdnull, so that run fails. - Conversion errors. If a column says
"abc"and the parameter isint, JUnit cannot convert it, and that run fails. - Too many cases in one test. Every row should test the same behavior. If a row needs different assertions, write a separate test instead.
- Exception cases mixed with normal cases. Dividing by zero throws an exception. Keep it in its own test with
assertThrows, not in the same table as normal results.
Exercises
Exercise
Write a parameterized test that checks Calculator.add with these cases: 0 + 0 = 0, 10 + -3 = 7, and 100 + 200 = 300. Name each run like "0 + 0 = 0".
Show answer
Use @ParameterizedTest(name = "{0} + {1} = {2}") with @CsvSource({"0, 0, 0", "10, -3, 7", "100, 200, 300"}) on a method void add(int a, int b, int expected) whose body is assertEquals(expected, calculator.add(a, b)); where calculator is a Calculator field.
Exercise
A test has @CsvSource({"apple, 3", "pear"}) and the method signature void check(String fruit, int count). What happens when it runs?
Show answer
The first run passes the values "apple" and 3. The second run fails with an error because the row "pear" has only one column and the method needs two parameters. JUnit does not fill in missing values.
Exercise
You want to test a method with null, an empty string, and the string " ". Which sources would you put on the test method?
Show answer
Put @NullAndEmptySource on the method to supply null and "", and add @ValueSource(strings = {" "}) for the spaces. The test then runs three times.