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.