0
0
JUnittesting~10 mins

@CsvSource for inline CSV data in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses JUnit's @CsvSource to run the same test method multiple times with different inline CSV data. It verifies that the sum of two numbers equals the expected result.

Test Code - JUnit 5
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 {

    @ParameterizedTest
    @CsvSource({
        "1, 2, 3",
        "4, 5, 9",
        "10, 20, 30"
    })
    void testAddition(int a, int b, int expectedSum) {
        int actualSum = a + b;
        assertEquals(expectedSum, actualSum, "Sum should match expected value");
    }
}
Execution Trace - 3 Steps
StepActionSystem StateAssertionResult
1Test starts with first CSV data set (1, 2, 3)JUnit test runner initializes test method with parameters a=1, b=2, expectedSum=3assertEquals(3, 1 + 2)PASS
2Test runs with second CSV data set (4, 5, 9)JUnit test runner initializes test method with parameters a=4, b=5, expectedSum=9assertEquals(9, 4 + 5)PASS
3Test runs with third CSV data set (10, 20, 30)JUnit test runner initializes test method with parameters a=10, b=20, expectedSum=30assertEquals(30, 10 + 20)PASS
Failure Scenario
Failing Condition: Expected sum does not match actual sum for any CSV data set
Execution Trace Quiz - 3 Questions
Test your understanding
What does the @CsvSource annotation do in this test?
ARuns the test only once with default values
BProvides multiple sets of input data inline for the test method
CReads CSV data from an external file
DSkips the test if CSV data is missing
Key Result
Using @CsvSource allows running the same test logic with multiple input values easily, improving test coverage and reducing code duplication.