Parameterization helps run the same test with different data without writing the test again and again. This saves time and keeps tests simple.
0
0
Why parameterization reduces test duplication in JUnit
Introduction
When you want to test a function with many input values.
When you need to check the same behavior for different user roles.
When you want to avoid copying the same test code multiple times.
When you want to keep your tests easy to maintain and update.
When you want to quickly add new test cases by just adding data.
Syntax
JUnit
@ParameterizedTest
@ValueSource(strings = {"input1", "input2", "input3"})
void testWithParameters(String input) {
// test code using input
}@ParameterizedTest tells JUnit to run the test multiple times with different data.
@ValueSource provides the data values for the test method parameters.
Examples
This test runs three times with numbers 1, 2, and 3 to check if they are positive.
JUnit
@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
void testNumbers(int number) {
assertTrue(number > 0);
}This test runs with pairs of fruit names and their expected lengths.
JUnit
@ParameterizedTest
@CsvSource({"apple, 5", "banana, 6", "cherry, 6"})
void testFruitLength(String fruit, int length) {
assertEquals(length, fruit.length());
}Sample Program
This test checks that none of the given strings are empty. It runs three times with different words.
JUnit
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; public class ParameterizedTestExample { @ParameterizedTest @ValueSource(strings = {"hello", "world", "JUnit"}) void testStringNotEmpty(String word) { assertFalse(word.isEmpty()); } }
OutputSuccess
Important Notes
Parameterization reduces code repetition by reusing the same test logic with different inputs.
It makes tests easier to read and maintain because you only change data, not code.
JUnit 5 provides many ways to supply parameters like @ValueSource, @CsvSource, and @MethodSource.
Summary
Parameterization runs one test multiple times with different data.
This avoids writing the same test many times for different inputs.
It keeps tests clean, simple, and easy to update.