What if you could test dozens of input cases with just one simple annotation?
Why @CsvSource for inline CSV data in JUnit? - Purpose & Use Cases
Imagine you have to test a function with many different inputs and expected results. You write each test case by hand, repeating similar code over and over.
For example, testing a calculator with 10 different pairs of numbers means writing 10 separate test methods.
This manual way is slow and boring. You might make mistakes copying and pasting. It's hard to see all test cases at once. Adding or changing test data means editing many places.
Also, the test code becomes long and messy, making it difficult to maintain.
@CsvSource lets you put all test data in one place, right inside your test method. You write the inputs and expected outputs as simple comma-separated values.
JUnit runs the test multiple times, once for each data row. This keeps your code clean and easy to update.
void testAdd() {
assertEquals(3, add(1, 2));
}
void testAdd2() {
assertEquals(5, add(2, 3));
}@ParameterizedTest
@CsvSource({"1, 2, 3", "2, 3, 5"})
void testAdd(int a, int b, int expected) {
assertEquals(expected, add(a, b));
}You can easily run many tests with different data in just one method, making your tests faster to write and simpler to read.
Testing a login function with multiple username and password combinations to check which ones succeed or fail, all in one neat test method.
Manual test cases for many inputs are slow and error-prone.
@CsvSource lets you write all test data inline, cleanly and compactly.
This makes tests easier to maintain and extend.