Parameterized Tests - anastasiamexa/Healthy-Coder-App GitHub Wiki
In JUnit 5, the @ParameterizedTest
annotation allows you to run a test multiple times with different sets of parameters. This is useful when you want to test a method or functionality with various inputs. Three commonly used sources for parameters with @ParameterizedTest
are @ValueSource
, @CsvSource
, and @CsvFileSource
.
Let's go through each of them:
@ValueSource
- Purpose: Provides a single parameterized value for each invocation of the test method.
- Usage: Use
@ValueSource
to specify an array of literal values as arguments.
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
public class MyParameterizedTest {
@ParameterizedTest
@ValueSource(ints = {1, 2, 3, 4, 5})
void testWithIntValues(int value) {
// Test logic with each value
}
}
@CsvSource
- Purpose: Allows you to provide multiple comma-separated values for each invocation of the test method.
- Usage: Use
@CsvSource
to specify sets of values in a CSV format.
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
public class MyParameterizedTest {
@ParameterizedTest
@CsvSource({"apple, 1", "banana, 2", "orange, 3"})
void testWithCsvSource(String fruit, int count) {
// Test logic with each pair of values
}
}
@CsvFileSource
- Purpose: Reads values from a CSV file and provides them as parameters for each invocation of the test method.
- Usage: Use
@CsvFileSource
to specify the path to a CSV file containing parameter values.
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvFileSource;
public class MyParameterizedTest {
@ParameterizedTest
@CsvFileSource(resources = "/test-data.csv")
void testWithCsvFileSource(String fruit, int count) {
// Test logic with each pair of values from the CSV file
}
}
In the above example, /test-data.csv
is the path to the CSV file in the classpath.
These parameterized tests allow you to run the same test logic with different sets of inputs, making it easier to cover various scenarios and edge cases. When a parameterized test is executed, JUnit will run the test multiple times, once for each set of parameters, and report any failures separately for each set of parameters.