Bird
Raised Fist0
Selenium Javatesting~10 mins

CSV data reading in Selenium Java - Test Execution Trace

Choose your learning style10 modes available
Test Overview

This test reads login data from a CSV file and uses it to perform login attempts on a web page. It verifies that the login page loads correctly and that the login button is clickable.

Test Code - TestNG with Selenium WebDriver
Selenium Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

public class CsvDataLoginTest {
    WebDriver driver;

    @BeforeClass
    public void setup() {
        driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
    }

    @DataProvider(name = "loginData")
    public Object[][] readCsvData() throws IOException {
        String path = "src/test/resources/login_data.csv";
        BufferedReader br = new BufferedReader(new FileReader(path));
        List<String[]> records = new ArrayList<>();
        String line;
        while ((line = br.readLine()) != null) {
            String[] fields = line.split(",");
            records.add(fields);
        }
        br.close();
        Object[][] data = new Object[records.size()][2];
        for (int i = 0; i < records.size(); i++) {
            data[i][0] = records.get(i)[0]; // username
            data[i][1] = records.get(i)[1]; // password
        }
        return data;
    }

    @Test(dataProvider = "loginData")
    public void testLogin(String username, String password) {
        driver.get("https://example.com/login");
        WebElement usernameInput = driver.findElement(By.id("username"));
        WebElement passwordInput = driver.findElement(By.id("password"));
        WebElement loginButton = driver.findElement(By.id("loginBtn"));

        Assert.assertTrue(usernameInput.isDisplayed(), "Username input should be visible");
        Assert.assertTrue(passwordInput.isDisplayed(), "Password input should be visible");

        usernameInput.clear();
        usernameInput.sendKeys(username);
        passwordInput.clear();
        passwordInput.sendKeys(password);

        Assert.assertTrue(loginButton.isEnabled(), "Login button should be enabled");
        loginButton.click();

        // For this example, we only verify that login button was clicked without error
    }

    @AfterClass
    public void teardown() {
        if (driver != null) {
            driver.quit();
        }
    }
Execution Trace - 9 Steps
StepActionSystem StateAssertionResult
1Test starts and WebDriver ChromeDriver instance is createdBrowser window opens, ready for navigation—PASS
2Reads CSV file 'login_data.csv' line by line to extract username and password pairsCSV file is read successfully, data stored in memory—PASS
3Navigates browser to 'https://example.com/login'Login page is loaded with username, password inputs and login button visibleCheck username and password input fields are displayedPASS
4Finds username input field and clears it, then enters username from CSVUsername input field contains the username value—PASS
5Finds password input field and clears it, then enters password from CSVPassword input field contains the password value—PASS
6Finds login button and verifies it is enabledLogin button is enabled and clickableLogin button is enabledPASS
7Clicks the login buttonLogin button clicked, page may navigate or respond—PASS
8Repeats steps 3-7 for each username/password pair from CSVAll login attempts performed—PASS
9Test ends and browser is closedBrowser window closed—PASS
Failure Scenario
Failing Condition: CSV file path is incorrect or file is missing
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test verify before entering login credentials?
AThat username and password input fields are visible
BThat the login button is clicked
CThat the page URL contains 'dashboard'
DThat the browser window is maximized
Key Result
Using a DataProvider to read CSV data allows running the same test multiple times with different inputs, improving test coverage and maintainability.

Practice

(1/5)
1. What is the main benefit of reading test data from a CSV file in Selenium Java tests?
easy
A. It automatically generates test reports.
B. It makes the test run faster by skipping validations.
C. It allows running the same test with multiple data sets easily.
D. It replaces the need for writing test scripts.

Solution

  1. 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.
  2. Step 2: Identify the benefit in test execution

    Using CSV data lets the same test run repeatedly with different inputs, improving coverage and maintenance.
  3. Final Answer:

    It allows running the same test with multiple data sets easily. -> Option C
  4. Quick Check:

    CSV data = multiple test inputs [OK]
Hint: CSV files separate data from code for easy test reuse [OK]
Common Mistakes:
  • Thinking CSV speeds up test execution
  • Believing CSV auto-generates reports
  • Assuming CSV replaces test scripts
2. Which of the following Java code snippets correctly reads a CSV file line by line using BufferedReader?
easy
A. BufferedReader br = new BufferedReader(new FileReader("data.csv")); String line = br.readLine(); while (line != null) { System.out.println(line); } br.close();
B. BufferedReader br = new BufferedReader(new FileReader("data.csv")); String line; while ((line = br.readLine()) != null) { System.out.println(line); } br.close();
C. BufferedReader br = new BufferedReader(new FileReader("data.csv")); while (br.readLine() != null) { System.out.println(line); } br.close();
D. BufferedReader br = new BufferedReader(new FileReader("data.csv")); for (int i=0; i<10; i++) { System.out.println(br.readLine()); } br.close();

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    BufferedReader br = new BufferedReader(new FileReader("data.csv")); String line; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); -> Option B
  4. Quick Check:

    Assign line inside while condition [OK]
Hint: Assign line inside while condition to avoid null errors [OK]
Common Mistakes:
  • Not assigning line inside the loop condition
  • Forgetting to update line inside the loop
  • Not checking for null before printing
3. Given the following code snippet, what will be the output if the CSV file contains:
name,age John,30 Jane,25

BufferedReader 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();
medium
A. name is age years old. John is 30 years old. Jane is 25 years old.
B. John is 30 years old. Jane is 25 years old.
C. name,age John,30 Jane,25
D. Error: ArrayIndexOutOfBoundsException

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    name is age years old. John is 30 years old. Jane is 25 years old. -> Option A
  4. Quick Check:

    Header line included in output [OK]
Hint: CSV header line is read like data unless skipped [OK]
Common Mistakes:
  • Assuming header line is skipped automatically
  • Expecting only data lines output
  • Ignoring split results causing errors
4. Identify the error in this CSV reading code snippet:
BufferedReader br = new BufferedReader(new FileReader("data.csv"));
String line = br.readLine();
while (line != null) {
  String[] values = line.split(",");
  System.out.println(values[0]);
}
medium
A. The code is correct and will print the first column.
B. The split method is used incorrectly; it should be split(';').
C. BufferedReader should be replaced with Scanner for CSV files.
D. The loop never updates 'line', causing an infinite loop.

Solution

  1. 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.
  2. Step 2: Consequence of missing update

    Without updating 'line' inside the loop, it causes an infinite loop printing the first line repeatedly.
  3. Final Answer:

    The loop never updates 'line', causing an infinite loop. -> Option D
  4. Quick Check:

    Update line inside loop to avoid infinite loop [OK]
Hint: Always update loop variable inside while to avoid infinite loops [OK]
Common Mistakes:
  • Forgetting to update 'line' inside the loop
  • Confusing split delimiter with semicolon
  • Thinking Scanner is mandatory for CSV
5. You want to read a CSV file with test data and run a Selenium test for each row. Which approach correctly integrates CSV reading with a test method in Java?
hard
A. 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.
B. Hardcode all test data inside the test method and ignore CSV files.
C. Read the CSV file inside the test method but do not loop; only use the first line.
D. Use BufferedReader to read CSV but do not close it after reading.

Solution

  1. 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.
  2. 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.
  3. 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 A
  4. Quick Check:

    Separate data reading and loop in test [OK]
Hint: Separate CSV reading method returns data list for test loops [OK]
Common Mistakes:
  • Hardcoding data inside tests reduces flexibility
  • Using only first CSV line ignores other data
  • Not closing BufferedReader causes resource leaks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard