Parameterized tests allow a single test method to be executed multiple times with different inputs. In JUnit Jupiter, you enable this behavior by annotating a test method with @ParameterizedTest and providing one or more sources of arguments. This helps remove duplication, improves coverage for edge cases, and keeps test code concise.
With parameterized tests, JUnit takes care of invoking the method repeatedly and performing type conversions for each set of arguments provided by the chosen source. You can still use standard assertions and lifecycle callbacks; only the way inputs are supplied changes.
The method annotated with @ParameterizedTest must not be private or static.
Java source and doc
Definition of ParameterizedTest(Version: junit-5 5.0.0) package org.junit.jupiter.params;
........
@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@API(status = EXPERIMENTAL, since = "5.0")
@TestTemplate
@ExtendWith(ParameterizedTestExtension.class)
public @interface ParameterizedTest {
String name() default "[{index}] {arguments}"; 1
}
Common argument sources (overview)
In addition to using @ParameterizedTest annotation which have to use another annotation to specify what is the source of the parameter values. We usually refer these annotation as 'argument source annotation'. Each of these annotation definitions are annotated with @ArgumentsSources(a repeatable annotation), which specify what is the implementation of ArgumentsProvider. The implementation of ArgumentsProvider is responsible to provide the arguments values and calling the test method multiple time. In a next tutorial we will implement our custom ArgumentsProvider.
Following is the list of argument source annotations.
@ValueSource - simple literals like strings and numbers
@CsvSource / @CsvFileSource - comma-separated values inline or from resources
@MethodSource - values produced by factory methods
@EnumSource - enum constants
@ArgumentsSource - custom providers via ArgumentsProvider
@NullSource, @EmptySource, @NullAndEmptySource - convenience sources for null/empty values
In the next tutorials we will see various examples related to @ParameterizedTest.
|