@CsvFileSource for external CSV in JUnit - Build an Automation Script
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvFileSource; import static org.junit.jupiter.api.Assertions.assertEquals; public class CsvFileSourceTest { @ParameterizedTest @CsvFileSource(resources = "/test-data.csv", numLinesToSkip = 1) void testStringLength(String input, int expectedLength) { assertEquals(expectedLength, input.length(), () -> "Expected length " + expectedLength + " but got " + input.length() + " for input: '" + input + "'"); } }
The test class CsvFileSourceTest uses JUnit 5's @ParameterizedTest to run the test method multiple times with different inputs.
The @CsvFileSource annotation loads data from the external CSV file test-data.csv located in src/test/resources. The resources path starts with a slash to indicate classpath root.
numLinesToSkip = 1 skips the header row in the CSV file.
The test method testStringLength receives two parameters: the input string and the expected length from each CSV row.
Inside the method, assertEquals checks if the actual string length matches the expected length, with a clear message to help debug if it fails.
This approach keeps tests clean, readable, and easy to maintain.
Extend the test to also verify that the input string is not empty for each CSV row