How to Use @CsvSource in JUnit for Parameterized Tests
Use
@CsvSource in JUnit to provide multiple sets of input data for a parameterized test method. Annotate the test method with @ParameterizedTest and list comma-separated values inside @CsvSource to run the test repeatedly with each data set.Syntax
The @CsvSource annotation takes an array of strings, each representing a comma-separated set of values for one test run. The test method parameters match the values in order.
@ParameterizedTest: Marks the method as a parameterized test.@CsvSource: Provides multiple sets of input data as strings.- Method parameters: Receive the values from each CSV line.
java
@ParameterizedTest
@CsvSource({"input1,expected1", "input2,expected2"})
void testMethod(String input, String expected) {
// test logic
}Example
This example shows a parameterized test that checks if a string is converted to uppercase correctly using @CsvSource. Each CSV line provides an input string and the expected uppercase result.
java
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; public class StringUtilsTest { @ParameterizedTest @CsvSource({ "hello, HELLO", "world, WORLD", "JUnit, JUNIT" }) void testToUpperCase(String input, String expected) { assertEquals(expected, input.toUpperCase()); } }
Output
3 tests passed
Common Pitfalls
- Forgetting to annotate the method with
@ParameterizedTestcauses the test not to run as parameterized. - Not matching the number of method parameters with CSV values leads to errors.
- Using commas inside CSV values without quotes breaks parsing.
- Empty strings must be represented as
""in CSV.
java
/* Wrong: Missing @ParameterizedTest */ @CsvSource({"a,1"}) void testWrong(String input, String expected) { // This will not run as parameterized test } /* Right: Correct annotations and matching parameters */ @ParameterizedTest @CsvSource({"a,1"}) void testRight(String input, String expected) { // Runs correctly }
Quick Reference
| Annotation | Purpose | Notes |
|---|---|---|
| @ParameterizedTest | Marks method as parameterized test | Required to enable parameterized execution |
| @CsvSource | Provides CSV data sets for test | Each string is one test case, values separated by commas |
| Method Parameters | Receive CSV values | Number and types must match CSV columns |
| Quotes in CSV | Handle commas or empty strings | Use double quotes to wrap values with commas or empty strings |
Key Takeaways
Always use @ParameterizedTest with @CsvSource to run parameterized tests in JUnit.
Match the number and types of method parameters exactly to the CSV values provided.
Wrap CSV values containing commas or empty strings in double quotes.
Each CSV line runs the test method once with those input values.
Common errors include missing @ParameterizedTest or mismatched parameters.