@CsvSource lets you run the same test many times with different data. It saves time and avoids repeating code.
0
0
@CsvSource for inline CSV data in JUnit
Introduction
You want to test a method with many input values quickly.
You have small sets of test data that fit well in your test code.
You want to check different combinations of inputs and expected outputs.
You want to keep test data close to the test logic for easy reading.
You want to avoid creating external files for simple test data.
Syntax
JUnit
@ParameterizedTest
@CsvSource({"value1, value2, expectedResult", "value3, value4, expectedResult2"})
void testMethod(type param1, type param2, type expected) {
// test code
}Each string inside @CsvSource represents one test case with comma-separated values.
Values are passed as parameters to the test method in the same order.
Examples
Tests addition with two sets of numbers.
JUnit
@ParameterizedTest
@CsvSource({"1, 2, 3", "4, 5, 9"})
void addTest(int a, int b, int expected) {
assertEquals(expected, a + b);
}Tests string length for different words.
JUnit
@ParameterizedTest
@CsvSource({"apple, 5", "banana, 6"})
void lengthTest(String word, int length) {
assertEquals(length, word.length());
}Tests boolean to uppercase string conversion.
JUnit
@ParameterizedTest
@CsvSource({"true, TRUE", "false, FALSE"})
void caseTest(boolean flag, String text) {
assertEquals(text, String.valueOf(flag).toUpperCase());
}Sample Program
This test runs three times with different numbers. It checks if adding two numbers equals the expected result.
JUnit
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; public class CalculatorTest { @ParameterizedTest @CsvSource({"1, 2, 3", "10, 20, 30", "5, 7, 12"}) void testAdd(int a, int b, int expected) { assertEquals(expected, a + b); } }
OutputSuccess
Important Notes
Use quotes around values if they contain spaces or special characters.
Empty strings can be represented by double quotes "" inside the CSV data.
Keep the number of CSV values and method parameters the same to avoid errors.
Summary
@CsvSource helps run one test many times with different data.
It keeps test data inside the test code for easy reading.
Use it for small, simple sets of test data without external files.