We can perform data driven using excel file with help of Apache POI library.
Here is the very basic program to perform data driven from excel file using Apache POI library.
Create a testdata.xlsx file in the C drive with following details:
Use below code to perform data driven from excel file:
Search Text
|
hello selenium
|
abhishek yadav qa
|
Java Source code:
package com.helloselenium.selenium.test; import java.io.*; import java.util.concurrent.TimeUnit; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class DataDrivenUsingExcelFile{ public static void main(String[] args) { WebDriver driver = new FirefoxDriver(); driver.get("http://www.google.com"); driver.manage().window().maximize(); WebElement searchbox = driver.findElement(By.name("q")); try { FileInputStream file = new FileInputStream(new File("C:\\testdata.xlsx")); XSSFWorkbook workbook = new XSSFWorkbook(file); XSSFSheet sheet = workbook.getSheetAt(0); for (int i=1; i <= sheet.getLastRowNum(); i++){ String keyword = sheet.getRow(i).getCell(0).getStringCellValue(); searchbox.sendKeys(keyword); searchbox.submit(); driver.manage().timeouts().implicitlyWait(10000, TimeUnit.MILLISECONDS); } workbook.close(); file.close(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } }
import java.io.*; import java.util.concurrent.TimeUnit;
import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver;
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
driver.navigate().to("http://www.google.com");
driver.manage().window().maximize();
WebElement searchbox = driver.findElement(By.name("q"));
FileInputStream file = new FileInputStream(new File("C:\\testdata.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
for (int i=1; i <= sheet.getLastRowNum(); i++){
String keyword = sheet.getRow(i).getCell(0).getStringCellValue();
searchbox.sendKeys(keyword);
searchbox.submit();
driver.manage().timeouts().implicitlyWait(10000, TimeUnit.MILLISECONDS);
workbook.close(); file.close();
1 Comments
Looks good.
ReplyDeleteWhat would you like to add in my list? I look forward to reading your comments below.