0
0
JUnittesting~5 mins

@CsvFileSource for external CSV in JUnit

Choose your learning style9 modes available
Introduction

@CsvFileSource helps you run the same test many times with different data from a CSV file. This saves time and avoids repeating code.

You want to test a function with many input values stored in a CSV file.
You have test data maintained separately from your code for easy updates.
You want to check how your code behaves with different sets of data without writing multiple tests.
You want to keep your test code clean and simple by loading data externally.
You want to share test data files across multiple test classes.
Syntax
JUnit
@ParameterizedTest
@CsvFileSource(resources = "/data.csv", numLinesToSkip = 1)
void testMethod(String input, int expected) {
    // test code here
}

resources points to the CSV file path inside your test resources folder.

numLinesToSkip is used to skip header lines in the CSV file.

Examples
This test runs once for each number in numbers.csv, checking if it is positive.
JUnit
@ParameterizedTest
@CsvFileSource(resources = "/numbers.csv")
void testWithNumbers(int number) {
    assertTrue(number > 0);
}
This test skips the first line (header) and tests login data from users.csv.
JUnit
@ParameterizedTest
@CsvFileSource(resources = "/users.csv", numLinesToSkip = 1)
void testUserLogin(String username, String password) {
    assertNotNull(username);
    assertNotNull(password);
}
Sample Program

This test reads three numbers per line from test-data.csv (skipping the header). It checks if the sum of a and b equals expectedSum.

JUnit
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvFileSource;

public class CsvFileSourceTest {

    @ParameterizedTest
    @CsvFileSource(resources = "/test-data.csv", numLinesToSkip = 1)
    void testSum(int a, int b, int expectedSum) {
        int actualSum = a + b;
        assertEquals(expectedSum, actualSum);
    }
}
OutputSuccess
Important Notes

Place your CSV file in src/test/resources folder so it is on the test classpath.

Use forward slashes '/' in the resource path, even on Windows.

Make sure the CSV file encoding is UTF-8 to avoid reading errors.

Summary

@CsvFileSource lets you run parameterized tests with data from CSV files.

It helps keep test data separate and easy to update.

Remember to skip headers if your CSV has them using numLinesToSkip.