CSV data reading in Selenium Java - Build an Automation Script
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.time.Duration; import static org.junit.jupiter.api.Assertions.assertEquals; public class LoginTest { private WebDriver driver; private WebDriverWait wait; @BeforeEach public void setUp() { driver = new ChromeDriver(); wait = new WebDriverWait(driver, Duration.ofSeconds(10)); } @AfterEach public void tearDown() { if (driver != null) { driver.quit(); } } @Test public void testLoginWithCsvData() throws IOException { driver.get("https://example.com/login"); String csvFile = "credentials.csv"; String username = ""; String password = ""; try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) { String headerLine = br.readLine(); // Read header String dataLine = br.readLine(); // Read first data row if (dataLine != null) { String[] values = dataLine.split(","); username = values[0].trim(); password = values[1].trim(); } } WebElement usernameInput = wait.until(ExpectedConditions.elementToBeClickable(By.id("username"))); usernameInput.clear(); usernameInput.sendKeys(username); WebElement passwordInput = wait.until(ExpectedConditions.elementToBeClickable(By.id("password"))); passwordInput.clear(); passwordInput.sendKeys(password); WebElement loginButton = wait.until(ExpectedConditions.elementToBeClickable(By.id("loginBtn"))); loginButton.click(); wait.until(ExpectedConditions.urlToBe("https://example.com/dashboard")); assertEquals("https://example.com/dashboard", driver.getCurrentUrl(), "User should be redirected to dashboard after login"); } }
This test uses Selenium WebDriver with JUnit 5 to automate login using credentials read from a CSV file.
In setUp(), we start the Chrome browser and create an explicit wait.
In the test method, we open the login page URL.
We read the CSV file using BufferedReader inside a try-with-resources block to ensure the file is closed properly.
We read the first data row after the header, split by comma, and extract username and password.
We wait explicitly for the username and password input fields to be clickable, then enter the values.
We click the login button and wait until the URL changes to the dashboard URL.
Finally, we assert that the current URL matches the expected dashboard URL, confirming successful login.
In tearDown(), we close the browser to clean up.
Now add data-driven testing to run the login test with 3 different username and password pairs from the CSV file.
Practice
Solution
Step 1: Understand the purpose of CSV data reading
CSV files store multiple sets of data externally, allowing tests to use different inputs without changing code.Step 2: Identify the benefit in test execution
Using CSV data lets the same test run repeatedly with different inputs, improving coverage and maintenance.Final Answer:
It allows running the same test with multiple data sets easily. -> Option CQuick Check:
CSV data = multiple test inputs [OK]
- Thinking CSV speeds up test execution
- Believing CSV auto-generates reports
- Assuming CSV replaces test scripts
Solution
Step 1: Check correct BufferedReader usage
BufferedReader br = new BufferedReader(new FileReader("data.csv")); String line; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); correctly initializes BufferedReader, reads each line into 'line', checks for null, and prints it inside the loop.Step 2: Identify errors in other options
BufferedReader br = new BufferedReader(new FileReader("data.csv")); while (br.readLine() != null) { System.out.println(line); } br.close(); uses 'line' without assignment; BufferedReader br = new BufferedReader(new FileReader("data.csv")); String line = br.readLine(); while (line != null) { System.out.println(line); } br.close(); never updates 'line' inside loop; BufferedReader br = new BufferedReader(new FileReader("data.csv")); for (int i=0; i<10; i++) { System.out.println(br.readLine()); } br.close(); reads fixed 10 lines without null check.Final Answer:
BufferedReader br = new BufferedReader(new FileReader("data.csv")); String line; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); -> Option BQuick Check:
Assign line inside while condition [OK]
- Not assigning line inside the loop condition
- Forgetting to update line inside the loop
- Not checking for null before printing
name,age
John,30
Jane,25BufferedReader br = new BufferedReader(new FileReader("data.csv"));
String line;
while ((line = br.readLine()) != null) {
String[] data = line.split(",");
System.out.println(data[0] + " is " + data[1] + " years old.");
}
br.close();Solution
Step 1: Understand CSV content and reading loop
The CSV has a header line 'name,age' and two data lines. The code reads each line and splits by comma.Step 2: Analyze output for each line
For the header line, data[0] = 'name', data[1] = 'age', so prints 'name is age years old.' Then for John and Jane lines, prints their names and ages accordingly.Final Answer:
name is age years old. John is 30 years old. Jane is 25 years old. -> Option AQuick Check:
Header line included in output [OK]
- Assuming header line is skipped automatically
- Expecting only data lines output
- Ignoring split results causing errors
BufferedReader br = new BufferedReader(new FileReader("data.csv"));
String line = br.readLine();
while (line != null) {
String[] values = line.split(",");
System.out.println(values[0]);
}Solution
Step 1: Review loop condition and update
The variable 'line' is assigned once before the loop but never updated inside the loop, so the condition never changes.Step 2: Consequence of missing update
Without updating 'line' inside the loop, it causes an infinite loop printing the first line repeatedly.Final Answer:
The loop never updates 'line', causing an infinite loop. -> Option DQuick Check:
Update line inside loop to avoid infinite loop [OK]
- Forgetting to update 'line' inside the loop
- Confusing split delimiter with semicolon
- Thinking Scanner is mandatory for CSV
Solution
Step 1: Separate data reading from test logic
Reading CSV in a separate method improves code reuse and clarity by returning all data as a list.Step 2: Loop over data in test method
The test method loops over the list of data arrays, running the test for each data set, enabling data-driven testing.Final Answer:
Read the CSV in a separate method that returns a List; then loop over this list in the test method to run tests with each data set. -> Option AQuick Check:
Separate data reading and loop in test [OK]
- Hardcoding data inside tests reduces flexibility
- Using only first CSV line ignores other data
- Not closing BufferedReader causes resource leaks
Ready to prove it?
Pass the test and this pattern moves unknown
