0
0
JUnittesting~10 mins

@CsvFileSource for external CSV in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test reads multiple sets of input data from an external CSV file using @CsvFileSource. It verifies that the sum of two numbers equals the expected result for each data row.

Test Code - JUnit 5
JUnit
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvFileSource;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class CalculatorTest {

    @ParameterizedTest
    @CsvFileSource(resources = "/data/sum-data.csv", numLinesToSkip = 1)
    void testSum(int a, int b, int expectedSum) {
        int actualSum = a + b;
        assertEquals(expectedSum, actualSum, () -> String.format("Sum of %d and %d should be %d", a, b, expectedSum));
    }
}
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test runner starts and loads the test class CalculatorTestJUnit test environment initialized-PASS
2Reads the CSV file '/data/sum-data.csv' skipping the header lineCSV file content loaded: rows of integers for a, b, expectedSum-PASS
3Executes testSum with first data row (a=1, b=2, expectedSum=3)Test method invoked with parameters (1, 2, 3)Check if 1 + 2 equals 3PASS
4Executes testSum with second data row (a=5, b=7, expectedSum=12)Test method invoked with parameters (5, 7, 12)Check if 5 + 7 equals 12PASS
5Executes testSum with third data row (a=10, b=15, expectedSum=25)Test method invoked with parameters (10, 15, 25)Check if 10 + 15 equals 25PASS
6All parameterized test cases completeTest report generated showing all tests passed-PASS
Failure Scenario
Failing Condition: CSV file path is incorrect or file is missing
Execution Trace Quiz - 3 Questions
Test your understanding
What does the @CsvFileSource annotation do in this test?
AIt provides test data from an external CSV file
BIt writes test results to a CSV file
CIt skips the test if the CSV file is missing
DIt generates random test data
Key Result
Using @CsvFileSource allows easy testing of multiple input sets from an external CSV file, making tests cleaner and more maintainable.