Reading Test Data from CSV

CSV File

Example

Keep data files in src/test/resources/testdata:

src/test/resources/testdata/logins.csv

email,password,expected
[email protected],Test@123,success
[email protected],wrong,Invalid email or password
[email protected],Test@123,Your account is locked

DataProvider from CSV

@DataProvider(name = "csvLogins")
public Object[][] csvLogins() throws IOException {
    List<String> lines = Files.readAllLines(Path.of("src/test/resources/testdata/logins.csv"));
    return lines.stream()
            .skip(1)                                   // header
            .filter(l -> !l.isBlank())
            .map(l -> l.split(",", -1))
            .toArray(Object[][]::new);
}

Example

The parsing runs here on a text block standing in for the file. Note the -1 in split: it keeps empty columns such as a blank email:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        String csv = """
            email,password,expected
            [email protected],Test@123,success
            ,Test@123,Please fill out this field.
            [email protected],,Please fill out this field.
            """;
        Object[][] data = csv.lines().skip(1).filter(l -> !l.isBlank())
                .map(l -> l.split(",", -1)).toArray(Object[][]::new);
        for (Object[] row : data) System.out.println(Arrays.toString(row) + " columns=" + row.length);

        System.out.println("Without -1: " + Arrays.toString("[email protected],,".split(",")));
    }
}

Output

[[email protected], Test@123, success] columns=3
[, Test@123, Please fill out this field.] columns=3
[[email protected], , Please fill out this field.] columns=3
Without -1: [[email protected]]