Saturday, December 6, 2025

thumbnail

Working with CSV Files in Java for Test Automation

 Why Use CSV Files for Test Automation?


CSV files are widely used in testing because they are:


Simple and human-readable


Easy to generate and maintain


Compatible with Excel and other tools


Great for data-driven tests


Using CSV allows you to separate test data from test scripts, making tests reusable and maintainable.


๐Ÿงฐ 1. Add a CSV Library (Optional)


Java can handle CSVs using core classes (BufferedReader, FileReader), but libraries simplify the process:


OpenCSV (most popular)


Apache Commons CSV


Maven dependency for OpenCSV:


<dependency>

    <groupId>com.opencsv</groupId>

    <artifactId>opencsv</artifactId>

    <version>5.8</version>

</dependency>


๐Ÿ“‚ 2. Sample CSV File


Example testdata.csv:


username,password,role

admin,Admin123,ADMIN

user1,User123,USER

guest,Guest123,GUEST


๐Ÿง‘‍๐Ÿ’ป 3. Reading CSV Data in Java

Using OpenCSV:

import com.opencsv.CSVReader;

import java.io.FileReader;

import java.util.List;


public class CsvReaderExample {

    public static void main(String[] args) throws Exception {

        CSVReader reader = new CSVReader(new FileReader("src/test/resources/testdata.csv"));

        List<String[]> records = reader.readAll();


        for (String[] record : records) {

            System.out.println("Username: " + record[0] + ", Password: " + record[1] + ", Role: " + record[2]);

        }


        reader.close();

    }

}


Using Java Core Classes:

import java.io.BufferedReader;

import java.io.FileReader;


public class CsvReaderCore {

    public static void main(String[] args) throws Exception {

        BufferedReader br = new BufferedReader(new FileReader("src/test/resources/testdata.csv"));

        String line;


        while ((line = br.readLine()) != null) {

            String[] data = line.split(",");

            System.out.println("Username: " + data[0] + ", Password: " + data[1] + ", Role: " + data[2]);

        }


        br.close();

    }

}


๐Ÿ“ 4. Writing to CSV


Using OpenCSV:


import com.opencsv.CSVWriter;

import java.io.FileWriter;


public class CsvWriterExample {

    public static void main(String[] args) throws Exception {

        CSVWriter writer = new CSVWriter(new FileWriter("output.csv"));


        String[] header = { "username", "password", "role" };

        writer.writeNext(header);


        String[] record1 = { "admin", "Admin123", "ADMIN" };

        String[] record2 = { "user1", "User123", "USER" };


        writer.writeNext(record1);

        writer.writeNext(record2);


        writer.close();

    }

}


๐Ÿ”— 5. Using CSV Data in Selenium Tests


CSV files are great for data-driven testing.


Example with Selenium:

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import com.opencsv.CSVReader;

import java.io.FileReader;


public class LoginTestCSV {

    public static void main(String[] args) throws Exception {

        WebDriver driver = new ChromeDriver();

        driver.get("https://example.com/login");


        CSVReader reader = new CSVReader(new FileReader("src/test/resources/testdata.csv"));

        String[] record;

        reader.readNext(); // Skip header


        while ((record = reader.readNext()) != null) {

            String username = record[0];

            String password = record[1];


            driver.findElement(By.id("username")).clear();

            driver.findElement(By.id("username")).sendKeys(username);

            driver.findElement(By.id("password")).clear();

            driver.findElement(By.id("password")).sendKeys(password);

            driver.findElement(By.id("loginButton")).click();


            // Add assertions here

        }


        reader.close();

        driver.quit();

    }

}


๐Ÿงช 6. Using CSV with TestNG DataProvider

@DataProvider(name = "loginData")

public Object[][] readCsvData() throws Exception {

    CSVReader reader = new CSVReader(new FileReader("src/test/resources/testdata.csv"));

    List<String[]> records = reader.readAll();

    reader.close();


    Object[][] data = new Object[records.size() - 1][2]; // exclude header

    for (int i = 1; i < records.size(); i++) {

        data[i - 1][0] = records.get(i)[0]; // username

        data[i - 1][1] = records.get(i)[1]; // password

    }

    return data;

}


@Test(dataProvider = "loginData")

public void loginTest(String username, String password) {

    driver.get("https://example.com/login");

    driver.findElement(By.id("username")).sendKeys(username);

    driver.findElement(By.id("password")).sendKeys(password);

    driver.findElement(By.id("loginButton")).click();

}



This makes your Selenium tests fully data-driven using CSV files.


⚡ 7. Best Practices


Keep CSV files in src/test/resources.


Use a header row to identify columns.


Use OpenCSV for easier parsing and writing.


Avoid hardcoding file paths; use Paths.get() for portability.


Combine with TestNG/JUnit DataProvider for scalable tests.


Use separate CSV files for different test scenarios.


๐ŸŽฏ Summary


CSV is simple, flexible, and widely used for test automation.


OpenCSV makes reading/writing CSVs in Java easy.


Use CSV for data-driven Selenium tests.


Combine with TestNG/JUnit for clean, maintainable, and scalable automated tests.

Learn Selenium with JAVA Training in Hyderabad

Read More

Using JSON for Test Data in Java Selenium

Writing Test Results into Excel Files in Selenium

Reading Test Data from Excel using Apache POI

๐Ÿ”Œ Data Handling and Advanced Concepts

Visit Our Quality Thought Institute in Hyderabad

Get Directions

Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

About

Search This Blog

Powered by Blogger.

Blog Archive