0
0
JUnittesting~3 mins

Why @CsvSource for inline CSV data in JUnit? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could test dozens of input cases with just one simple annotation?

The Scenario

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.

The Problem

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.

The Solution

@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.

Before vs After
Before
void testAdd() {
  assertEquals(3, add(1, 2));
}
void testAdd2() {
  assertEquals(5, add(2, 3));
}
After
@ParameterizedTest
@CsvSource({"1, 2, 3", "2, 3, 5"})
void testAdd(int a, int b, int expected) {
  assertEquals(expected, add(a, b));
}
What It Enables

You can easily run many tests with different data in just one method, making your tests faster to write and simpler to read.

Real Life Example

Testing a login function with multiple username and password combinations to check which ones succeed or fail, all in one neat test method.

Key Takeaways

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.