0
0
JUnittesting~15 mins

@CsvSource for inline CSV data in JUnit - Build an Automation Script

Choose your learning style9 modes available
Test addition method with multiple inputs using @CsvSource
Preconditions (2)
Step 1: Create a parameterized test method annotated with @ParameterizedTest
Step 2: Use @CsvSource to provide inline CSV data with pairs of integers and their expected sum
Step 3: For each CSV row, call add(a, b) with the first two values
Step 4: Assert that the result equals the expected sum (third value)
✅ Expected Result: The test passes for all CSV input rows verifying the add method returns correct sums
Automation Requirements - JUnit 5
Assertions Needed:
Assert that add(a, b) equals expected sum for each CSV input row
Best Practices:
Use @ParameterizedTest with @CsvSource for inline data
Use descriptive test method names
Use assertions from org.junit.jupiter.api.Assertions
Keep test method simple and focused
Automated Solution
JUnit
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class CalculatorTest {

    // Method to test
    public int add(int a, int b) {
        return a + b;
    }

    @ParameterizedTest(name = "add({0}, {1}) = {2}")
    @CsvSource({
        "1, 2, 3",
        "5, 7, 12",
        "10, 15, 25",
        "0, 0, 0",
        "-1, 1, 0"
    })
    void testAdd(int a, int b, int expectedSum) {
        assertEquals(expectedSum, add(a, b));
    }
}

This test class CalculatorTest contains a simple add method to add two integers.

The test method testAdd is annotated with @ParameterizedTest and @CsvSource to provide multiple sets of input data inline as CSV strings.

Each CSV row has three values: the first two are inputs a and b, and the third is the expected sum.

The test runs once for each CSV row, calling add(a, b) and asserting the result equals expectedSum.

This approach keeps the test concise, readable, and easy to add more test cases by just adding more CSV lines.

Common Mistakes - 4 Pitfalls
Using @CsvFileSource instead of @CsvSource for inline data
Not matching the number of parameters in the test method to CSV columns
Using string parameters without converting to int for numeric tests
Hardcoding expected results inside the test method instead of using CSV
Bonus Challenge

Now add data-driven testing with 3 different inputs including negative numbers and zero

Show Hint