Parameterized tests let a single test method run multiple times with different sets of input data, avoiding the need to duplicate near-identical test methods for each case.
Key Points: • In JUnit 4, you annotate the class with @RunWith(Parameterized.class) and provide a static method annotated @Parameters that returns a collection of argument sets. • In JUnit 5, @ParameterizedTest replaces @Test, paired with a source annotation like @ValueSource, @CsvSource, or @MethodSource to supply the data. • Each set of parameters triggers one full execution of the test method, with results reported per invocation. • Parameterized tests reduce duplication and make it easy to cover edge cases like boundary values, nulls, and typical inputs in one place. • JUnit 5's approach is generally preferred over JUnit 4's for its more flexible and readable data-source annotations.
Example: A test validating an isEven(int) method could use @CsvSource({"2,true", "3,false", "0,true"}) to run the same assertion logic against three different input/expected-output pairs.
Code Example:
@ParameterizedTest
@CsvSource({"2,true", "3,false", "0,true"})
void checksEvenNumbers(int input, boolean expected) {
assertEquals(expected, MathUtils.isEven(input));
}Interview Tip: A concise interview answer is:
"Parameterized tests run the same test logic against multiple sets of input data instead of duplicating the method per case. In JUnit 5 I use @ParameterizedTest with a source like @CsvSource or @MethodSource to supply the different argument combinations."