Selenium Interview Q&A
Q1. What is Selenium? What are its components?
A: Selenium is an open-source automation testing tool for web applications. Its main components are:
- Selenium IDE – Record & playback tool.
- Selenium RC (deprecated) – Older client-server architecture.
- Selenium WebDriver – Modern, widely used API for browser automation.
- Selenium Grid – Parallel test execution across multiple machines/browsers.
Q2. Difference between Selenium WebDriver and Selenium RC?
A:
- WebDriver directly communicates with the browser using native API → faster & more efficient.
- RC used a server as a middle layer → slower & deprecated.
Q3. Which programming languages are supported by Selenium?
A: Java, Python, C#, Ruby, JavaScript, Kotlin, etc. (Most common: Java & Python).
WebDriver Basics
Q4. How do you launch a browser in Selenium WebDriver?
A (Java Example):
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
Q5. Difference between driver.close() and driver.quit()?
-
driver.close()→ Closes current active browser window. -
driver.quit()→ Closes all browser windows opened by WebDriver and ends the session.
Q6. How do you locate elements in Selenium?
A: Using locators:
-
id -
name -
className -
tagName -
linkText/partialLinkText -
cssSelector -
xpath
Example:
driver.findElement(By.id("username"));
driver.findElement(By.xpath("//input[@name='q']"));
Waits & Synchronization
Q7. What is the difference between Implicit Wait and Explicit Wait?
- Implicit Wait → Sets a default waiting time for all elements.
- Explicit Wait → Waits for a specific condition for a specific element.
Example (Explicit Wait in Java):
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("username")));
Q8. What is Fluent Wait in Selenium?
A: It checks for a condition at regular intervals until timeout. It allows polling frequency & ignoring exceptions.
Practical Questions
Q9. How do you handle dropdowns in Selenium?
A (Java Example):
WebElement dropdown = driver.findElement(By.id("country"));
Select select = new Select(dropdown);
select.selectByVisibleText("India");
select.selectByIndex(2);
select.selectByValue("US");
Q10. How do you handle alerts/popups in Selenium?
Alert alert = driver.switchTo().alert();
alert.accept(); // OK
alert.dismiss(); // Cancel
alert.sendKeys("text"); // For prompt
Q11. How do you handle multiple browser windows?
String mainWindow = driver.getWindowHandle();
Set<String> allWindows = driver.getWindowHandles();
for(String win : allWindows){
driver.switchTo().window(win);
}
Q12. How do you perform mouse hover or drag-and-drop in Selenium?
Actions actions = new Actions(driver);
actions.moveToElement(driver.findElement(By.id("menu"))).perform(); // Hover
actions.dragAndDrop(sourceElement, targetElement).perform(); // Drag & Drop
Advanced Questions
Q13. What is Page Object Model (POM)?
A: A design pattern in Selenium that creates separate classes for each page, storing locators and methods.
It improves reusability & maintainability.
Q14. How do you handle dynamic elements in Selenium?
- Use XPath with contains(), starts-with()
-
Use CSS selectors with partial attributes
Example:
driver.findElement(By.xpath("//input[contains(@id,'username')]"));
Q15. How do you capture screenshots in Selenium?
File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("./screenshot.png"));
Q16. How do you run Selenium tests in parallel?
-
Using TestNG
parallel=testsorparallel=classes - Using Selenium Grid
Q17. What are limitations of Selenium?
- Supports only web applications (not desktop apps).
- Cannot automate Captcha, OTP, Barcode directly.
- No inbuilt reporting → Need tools like TestNG/Allure/Extent Reports.
- No direct support for image comparison.
Behavioral / Experience-Based
Q18. Tell me about your Selenium framework.
👉 Answer should cover:
- Framework type: Hybrid / Data-driven / Keyword-driven / POM + TestNG
- Features used: Maven/Gradle for dependencies, TestNG for test management, Extent/Allure for reporting, Jenkins for CI/CD, Git for version control.
Q19. What challenges did you face in Selenium automation?
Examples you can mention:
- Handling dynamic elements (solution: smart XPath/CSS).
- Browser compatibility issues (solution: Selenium Grid).
- Synchronization issues (solution: Explicit/Fluent waits).
- Test data management (solution: Excel/CSV/Database integration).
Q20. How do you integrate Selenium with CI/CD?
- Use Jenkins/GitHub Actions to trigger builds.
-
Configure Maven commands:
mvn clean test. - Generate reports after test execution.
Intro
Interviewer: Tell me about yourself.
You (Sample Answer):
“I have 2 years of experience in software testing, with a focus on automation using Selenium WebDriver and manual testing. I have worked on web applications across [domain – e.g., healthcare, e-commerce]. My skills include test case design, defect reporting, API testing with Postman, and automation framework development using Selenium with TestNG. I have also integrated my scripts with Jenkins for CI/CD and generated reports using Extent/Allure. I’m comfortable with Agile methodology and actively participated in sprint planning and daily standups.”
Core Selenium
Interviewer: What is Selenium WebDriver, and how is it different from Selenium RC?
You:
“Selenium WebDriver is a tool used to automate browser actions. It communicates directly with the browser using native APIs. Unlike Selenium RC, WebDriver does not need a server in between, which makes it faster and more efficient. Selenium RC is now deprecated, and WebDriver is widely used.”
Interviewer: What locators have you used most often? Which one do you prefer?
You:
“I mostly use XPath and CSS selectors for dynamic elements, but I prefer id or name when available since they are faster and more reliable. If the attributes are dynamic, I use XPath functions like contains(), starts-with(), or CSS with partial matches.”
Interviewer: What is the difference between driver.close() and driver.quit()?
You:
“driver.close() closes only the current active browser window, while driver.quit() closes all browser windows opened by WebDriver and ends the session.”
Waits & Synchronization
Interviewer: How do you handle synchronization issues in Selenium?
You:
“I use different types of waits. For general waits, I use implicit wait. For specific conditions, I use explicit wait with WebDriverWait and ExpectedConditions. If I need polling intervals or to ignore exceptions, I use FluentWait. This helps avoid NoSuchElementException or ElementNotInteractableException.”
Practical Coding
Interviewer: Can you write a snippet to select a value from a dropdown?
You (Java Example):
WebElement dropdown = driver.findElement(By.id("country"));
Select select = new Select(dropdown);
select.selectByVisibleText("India");
Interviewer: How would you handle multiple browser windows?
You:
String mainWindow = driver.getWindowHandle();
Set<String> allWindows = driver.getWindowHandles();
for(String win : allWindows){
if(!win.equals(mainWindow)){
driver.switchTo().window(win);
}
}
Framework & Tools
Interviewer: Can you explain your Selenium automation framework?
You:
“My framework is a Hybrid framework combining Page Object Model and Data-Driven approach. I use Maven for dependency management, TestNG for test execution, and Extent/Allure for reporting. I have utilities for reading data from Excel and property files. For CI/CD, I integrated it with Jenkins to trigger test runs automatically. The framework supports parallel execution using TestNG and Selenium Grid.”
Interviewer: How do you manage test data in your automation framework?
You:
“I maintain test data in Excel/CSV files and sometimes in property files for configuration values. I also parameterize tests using TestNG @DataProvider. This helps in reusing the same script with multiple sets of data.”
Challenges
Interviewer: What challenges did you face in Selenium automation, and how did you solve them?
You (Sample Examples):
-
Dynamic elements: Solved using robust XPath with
contains()or CSS partial selectors. -
Page load delays: Used explicit waits like
visibilityOfElementLocated. - Cross-browser issues: Used Selenium Grid to test in different browsers.
- Large test execution time: Implemented parallel execution with TestNG.
CI/CD
Interviewer: How do you integrate Selenium tests with Jenkins?
You:
“I created a Jenkins job where I linked our GitHub repository. I configured Maven commands like mvn clean test in the build step. After execution, the job generates Extent/Allure reports, which are published as part of Jenkins build results. This setup ensures automation tests run automatically after every code push.”
Behavioral
Interviewer: Why should we hire you?
You:
“I bring hands-on experience in both manual and automation testing. I have built and executed automation frameworks with Selenium and TestNG, handled challenges with dynamic applications, and worked in Agile teams. With my 2 years of experience, I can quickly contribute to automation efforts, improve test coverage, and help in delivering quality products.”
Must-Practice Selenium Coding Tasks
1. Launch Browser & Open URL
- Open Chrome/Firefox
- Navigate to Google
- Maximize window & print the page title
2. Locating Elements
- Locate by id, name, class, CSS, XPath
- Example: search box on Google, login fields on a demo site
3. Login Automation
- Open login page
- Enter username, password
- Click Login button
-
Validate successful login using
asserton page title / welcome message
4. Handling Dropdowns (Using Select class)
- Select by index, value, visible text
- Example: select “India” from a country dropdown
5. Handling Checkboxes & Radio Buttons
- Select a checkbox → verify it is selected
- Select a radio button → verify mutual exclusivity
6. Handling Alerts/Popups
-
Simple alert →
accept() -
Confirmation alert →
dismiss() -
Prompt alert →
sendKeys("text")
7. Handling Multiple Windows/Tabs
- Click link that opens a new tab
- Switch to child window → perform action
- Switch back to main window
8. Handling Frames/iFrames
- Switch to frame by index, name, or WebElement
- Perform action inside frame
- Switch back to default content
9. Mouse & Keyboard Actions (Actions Class)
- Mouse hover (moveToElement)
- Drag & drop
- Double click
- Right click (context click)
-
Send keys with
Keys.ENTER
10. Waits (Synchronization)
- Implicit wait example
- Explicit wait → wait for element to be clickable
- Fluent wait → with polling interval
11. Working with Web Tables
- Find number of rows & columns
- Read data from a specific cell
- Iterate through all rows & print values
12. Handling Dynamic Elements
-
Write XPath with
contains(),starts-with(),last(),following-sibling - Example: selecting a search suggestion from Google auto-suggest list
13. File Upload
-
Use
sendKeys("path/to/file")on<input type="file"> - Or handle OS pop-up with Robot class / AutoIt (if asked)
14. Screenshot Capture
- Take screenshot on failure
- Save with dynamic filename (timestamp)
15. Data-Driven Testing (DDT)
-
Use TestNG
@DataProvider - Read data from Excel (Apache POI)
- Run the same test with multiple inputs
16. Page Object Model (POM) Implementation
- Create separate class for each page
- Store locators & methods inside page classes
- Use them in test class
17. Parallel Execution
- Run 2–3 tests in parallel using TestNG XML
- Example: login test + search test
18. End-to-End Flow Automation
- Open e-commerce site (like demo.opencart, saucedemo, or Amazon)
- Search product → Add to cart → Checkout → Validate order success
19. Reporting
- Integrate Extent Reports or Allure
- Generate a test execution report
20. Jenkins Integration
- Create a Maven project
-
Run
mvn clean test - View test results in Jenkins
Selenium 20 Coding Tasks with Answers (Java + Selenium)
1. Launch Browser & Open URL
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com");
System.out.println("Title: " + driver.getTitle());
2. Locating Elements
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.name("password")).sendKeys("admin123");
driver.findElement(By.className("login-btn")).click();
driver.findElement(By.cssSelector("input[type='text']")).sendKeys("Search");
driver.findElement(By.xpath("//button[text()='Login']")).click();
3. Login Automation
driver.get("https://opensource-demo.orangehrmlive.com/");
driver.findElement(By.id("txtUsername")).sendKeys("Admin");
driver.findElement(By.id("txtPassword")).sendKeys("admin123");
driver.findElement(By.id("btnLogin")).click();
String expected = "Dashboard";
String actual = driver.getTitle();
Assert.assertTrue(actual.contains(expected));
4. Handling Dropdowns
WebElement country = driver.findElement(By.id("country"));
Select select = new Select(country);
select.selectByVisibleText("India");
select.selectByIndex(2);
select.selectByValue("US");
5. Handling Checkboxes & Radio Buttons
WebElement checkbox = driver.findElement(By.id("subscribe"));
checkbox.click();
System.out.println("Checkbox selected: " + checkbox.isSelected());
WebElement radio = driver.findElement(By.id("male"));
radio.click();
System.out.println("Radio selected: " + radio.isSelected());
6. Handling Alerts
Alert alert = driver.switchTo().alert();
alert.accept(); // OK
alert.dismiss(); // Cancel
alert.sendKeys("Hello"); // For prompt alerts
7. Handling Multiple Windows
String main = driver.getWindowHandle();
driver.findElement(By.linkText("Open New Window")).click();
for(String win : driver.getWindowHandles()){
if(!win.equals(main)){
driver.switchTo().window(win);
System.out.println("Child window title: " + driver.getTitle());
driver.close();
}
}
driver.switchTo().window(main);
8. Handling Frames/iFrames
driver.switchTo().frame("frame1");
driver.findElement(By.id("username")).sendKeys("testUser");
driver.switchTo().defaultContent();
9. Mouse & Keyboard Actions
Actions actions = new Actions(driver);
WebElement menu = driver.findElement(By.id("menu"));
actions.moveToElement(menu).perform(); // Hover
WebElement src = driver.findElement(By.id("source"));
WebElement dest = driver.findElement(By.id("target"));
actions.dragAndDrop(src, dest).perform();
actions.doubleClick(driver.findElement(By.id("doubleClickBtn"))).perform();
actions.contextClick(driver.findElement(By.id("rightClickBtn"))).perform();
actions.sendKeys(Keys.ENTER).perform();
10. Waits
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));
WebElement el = wait.until(ExpectedConditions.elementToBeClickable(By.id("login")));
Wait<WebDriver> fwait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(20))
.pollingEvery(Duration.ofSeconds(2))
.ignoring(NoSuchElementException.class);
WebElement ele = fwait.until(d -> d.findElement(By.id("username")));
11. Web Tables
List<WebElement> rows = driver.findElements(By.xpath("//table[@id='data']/tbody/tr"));
List<WebElement> cols = driver.findElements(By.xpath("//table[@id='data']/thead/tr/th"));
System.out.println("Rows: " + rows.size());
System.out.println("Cols: " + cols.size());
for(WebElement row : rows){
System.out.println(row.getText());
}
12. Handling Dynamic Elements
driver.findElement(By.xpath("//input[contains(@id,'user')]")).sendKeys("test");
driver.findElement(By.cssSelector("div[class*='login']")).click();
driver.findElement(By.xpath("//button[starts-with(@id,'btn_')]")).click();
13. File Upload
WebElement upload = driver.findElement(By.id("fileUpload"));
upload.sendKeys("C:\\Users\\Pushkar\\Documents\\testfile.txt");
14. Screenshot Capture
File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
File dest = new File("screenshot_" + System.currentTimeMillis() + ".png");
Files.copy(src.toPath(), dest.toPath());
15. Data-Driven Testing (TestNG + DataProvider)
@DataProvider(name="loginData")
public Object[][] getData(){
return new Object[][] { {"Admin","admin123"}, {"User","user123"} };
}
@Test(dataProvider="loginData")
public void loginTest(String user, String pass){
driver.findElement(By.id("username")).sendKeys(user);
driver.findElement(By.id("password")).sendKeys(pass);
driver.findElement(By.id("login")).click();
}
16. Page Object Model (POM)
// LoginPage.java
public class LoginPage {
WebDriver driver;
By username = By.id("username");
By password = By.id("password");
By loginBtn = By.id("login");
public LoginPage(WebDriver driver){ this.driver = driver; }
public void login(String user, String pass){
driver.findElement(username).sendKeys(user);
driver.findElement(password).sendKeys(pass);
driver.findElement(loginBtn).click();
}
}
// TestClass.java
LoginPage lp = new LoginPage(driver);
lp.login("Admin","admin123");
17. Parallel Execution (TestNG XML)
<suite name="ParallelTests" parallel="tests" thread-count="2">
<test name="ChromeTest">
<parameter name="browser" value="chrome"/>
<classes>
<class name="tests.LoginTest"/>
</classes>
</test>
<test name="FirefoxTest">
<parameter name="browser" value="firefox"/>
<classes>
<class name="tests.LoginTest"/>
</classes>
</test>
</suite>
18. End-to-End Flow
driver.get("https://www.saucedemo.com/");
driver.findElement(By.id("user-name")).sendKeys("standard_user");
driver.findElement(By.id("password")).sendKeys("secret_sauce");
driver.findElement(By.id("login-button")).click();
driver.findElement(By.xpath("//div[text()='Sauce Labs Backpack']")).click();
driver.findElement(By.id("add-to-cart-sauce-labs-backpack")).click();
driver.findElement(By.className("shopping_cart_link")).click();
driver.findElement(By.id("checkout")).click();
driver.findElement(By.id("first-name")).sendKeys("John");
driver.findElement(By.id("last-name")).sendKeys("Doe");
driver.findElement(By.id("postal-code")).sendKeys("12345");
driver.findElement(By.id("continue")).click();
driver.findElement(By.id("finish")).click();
19. Reporting (Extent Reports Example)
ExtentReports extent = new ExtentReports();
ExtentSparkReporter spark = new ExtentSparkReporter("report.html");
extent.attachReporter(spark);
ExtentTest test = extent.createTest("Login Test");
test.pass("Opened browser");
test.fail("Login failed");
extent.flush();
20. Jenkins Integration
- Push project to GitHub (Maven + TestNG).
- Jenkins → Create job → Configure Git repo.
- In Build Step → use:
mvn clean test
- Post-build → Publish HTML/Extent reports.
Project Structure
selenium-testng-framework/
│── pom.xml
│── testng.xml
│── src
│ ├── main
│ │ └── java
│ │ └── pages # Page Object Model (POM) classes
│ │ └── LoginPage.java
│ └── test
│ └── java
│ ├── tests # Test classes
│ │ └── LoginTest.java
│ └── utils # Utility classes
│ └── ExtentManager.java
│── reports/ # Auto-generated test reports
📄 pom.xml (Dependencies)
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.pushkar.selenium</groupId>
<artifactId>selenium-testng-framework</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- Selenium -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.25.0</version>
</dependency>
<!-- TestNG -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.10.2</version>
<scope>test</scope>
</dependency>
<!-- Extent Reports -->
<dependency>
<groupId>com.aventstack</groupId>
<artifactId>extentreports</artifactId>
<version>5.1.1</version>
</dependency>
<!-- WebDriver Manager (auto driver setup) -->
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>5.9.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Maven Compiler Plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
<!-- Maven Surefire Plugin for TestNG -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.2.5</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
</project>
📄 testng.xml
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Selenium Suite" parallel="false">
<test name="Login Test">
<classes>
<class name="tests.LoginTest"/>
</classes>
</test>
</suite>
📄 pages/LoginPage.java
package pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPage {
WebDriver driver;
By username = By.id("user-name");
By password = By.id("password");
By loginBtn = By.id("login-button");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public void login(String user, String pass) {
driver.findElement(username).sendKeys(user);
driver.findElement(password).sendKeys(pass);
driver.findElement(loginBtn).click();
}
}
📄 utils/ExtentManager.java
package utils;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.reporter.ExtentSparkReporter;
public class ExtentManager {
private static ExtentReports extent;
public static ExtentReports getInstance() {
if (extent == null) {
ExtentSparkReporter reporter = new ExtentSparkReporter("reports/extent-report.html");
reporter.config().setReportName("Automation Test Report");
reporter.config().setDocumentTitle("Selenium Framework Report");
extent = new ExtentReports();
extent.attachReporter(reporter);
}
return extent;
}
}
📄 tests/LoginTest.java
package tests;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.*;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.chrome.ChromeDriver;
import pages.LoginPage;
import utils.ExtentManager;
public class LoginTest {
WebDriver driver;
ExtentReports extent;
ExtentTest test;
@BeforeSuite
public void setupReport() {
extent = ExtentManager.getInstance();
}
@BeforeMethod
public void setup() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.saucedemo.com/");
}
@Test
public void loginTest() {
test = extent.createTest("Login Test");
LoginPage lp = new LoginPage(driver);
lp.login("standard_user", "secret_sauce");
String title = driver.getTitle();
if (title.contains("Swag Labs")) {
test.log(Status.PASS, "Login successful");
} else {
test.log(Status.FAIL, "Login failed");
}
}
@AfterMethod
public void tearDown() {
driver.quit();
}
@AfterSuite
public void flushReport() {
extent.flush();
}
}
Run Instructions
- Clone project from GitHub (or create new Maven project).
-
Run tests with:
mvn clean test -
Open report:
reports/extent-report.htmlUsing Excel (Apache POI)
You can read data from Excel and pass it to TestNG
@DataProvider✅ Step 1: Add dependency in
pom.xml<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.3.0</version>
</dependency>✅ Step 2: Create Excel File
📄
TestData.xlsx→ Sheet Name:LoginDataUsername Password standard_user secret_sauce locked_out_user secret_sauce problem_user secret_sauce ✅ Step 3: Utility Class to Read Excel
package utils;
import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelUtils {
public static Object[][] getExcelData(String filePath, String sheetName) {
Object[][] data = null;
try (FileInputStream fis = new FileInputStream(filePath);
Workbook workbook = new XSSFWorkbook(fis)) {
Sheet sheet = workbook.getSheet(sheetName);
int rowCount = sheet.getPhysicalNumberOfRows();
int colCount = sheet.getRow(0).getPhysicalNumberOfCells();
data = new Object[rowCount - 1][colCount];
for (int i = 1; i < rowCount; i++) {
Row row = sheet.getRow(i);
for (int j = 0; j < colCount; j++) {
data[i - 1][j] = row.getCell(j).getStringCellValue();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
}✅ Step 4: Test Class with DataProvider
package tests;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import utils.ExcelUtils;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
public class ExcelDataDrivenTest {
@DataProvider(name = "excelData")
public Object[][] getData() {
return ExcelUtils.getExcelData("src/test/resources/TestData.xlsx", "LoginData");
}
@Test(dataProvider = "excelData")
public void loginTest(String username, String password) {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.saucedemo.com/");
driver.findElement(By.id("user-name")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
driver.findElement(By.id("login-button")).click();
System.out.println("Login test done for user: " + username);
driver.quit();
}
}Using CSV File
✅ Step 1: Add OpenCSV dependency
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>5.9</version>
</dependency>✅ Step 2: Sample CSV file –
login.csvusername,password
standard_user,secret_sauce
locked_out_user,secret_sauce
problem_user,secret_sauce✅ Step 3: Read CSV and Use in TestNG
package tests;
import com.opencsv.CSVReader;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.FileReader;
import java.util.List;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
public class CSVDataDrivenTest {
@DataProvider(name = "csvData")
public Object[][] getData() throws Exception {
CSVReader reader = new CSVReader(new FileReader("src/test/resources/login.csv"));
List<String[]> allData = reader.readAll();
Object[][] data = new Object[allData.size() - 1][2];
for (int i = 1; i < allData.size(); i++) {
data[i - 1][0] = allData.get(i)[0];
data[i - 1][1] = allData.get(i)[1];
}
return data;
}
@Test(dataProvider = "csvData")
public void loginTest(String username, String password) {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.get("https://www.saucedemo.com/");
driver.findElement(By.id("user-name")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
driver.findElement(By.id("login-button")).click();
System.out.println("CSV login done for: " + username);
driver.quit();
}
}📊 Benefits of DDT
Benefit Description ✅ Reusability One script, multiple data sets ✅ Maintainability Data stored outside the script ✅ Scalability Easily add new data without editing code ✅ Automation Coverage Quickly validate different user scenarios Interview Tip:
Common Question: “How do you implement Data-Driven Testing in Selenium?”
Sample Answer:“I implement data-driven testing using TestNG’s DataProvider or Apache POI for Excel-based data.
I externalize test data in Excel sheets, fetch them dynamically at runtime, and pass them
into my test methods. This helps me run the same test with multiple input combinations without
modifying the test logic.”
I capture screenshots automatically when a test fails using a screenshot utility function.
No comments:
Post a Comment