SlideShare a Scribd company logo
Selenium Webdriver with Data Driven Framework
Data Driven Framework:
 Externalized the data from the scripts.
 Framework will function based on the number of combination of test data available in external files.
 Scripts should not be modified for any addition of test case or scenario if the transaction or action (and
the navigation involved in the transaction) remains same.
In this example for compiere 3.8.0 login contains
 Config and ScreenShots folders in src folder - Contains test and configure data file
 testApps and Utils packages in src – Contains java classes for functional testing.
 log4j.xml - Configure file for log 4j
 build.xml – To build the automation source.
 Final.xml – xml to run the automation script.
 Build folder - Created by build.xml
 test-output folder - Created for every testNG execution
 testng-xslt - Created from testing-results.xml in test-output folder for every testNG execution.
 SeleniumLog.log - Created/appended for the for every testNG execution and writes the log.
1) Config folder in src folder
It contains the object repository property and test data sheet for the test.
Login.Xls (Test Data)
ObjectRep.Property file
#URL
URL = http://192.168.0.87:8080/
#Login Screen Objects
LOGIN.USERNAME = 0|0|User
LOGIN.PASSWORD = 0|0|Password
LOGIN.ROLE = //input[@name='0|0|AD_Role_ID']
LOGIN.DATE = //tr[5]/td[2]/table/tbody/tr/td/input
LOGIN.OKBUTTON = 0|0|Ok
LOGIN.HOME = WindowName
2) ScreenShots folders in src folder
It contains the screenshot taken it the test execution for every test cases.
3) testApps package in src
It contains the java classes for functional testing (test script).
Login.java
package testApps;
import java.awt.AWTException;
import java.awt.HeadlessException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import Utils.ScreenShot;
import Utils.ObjectRep;
import Utils.DataDriven;
public class Login {
public int homePage(WebDriver driver,String baseUrl) throws IOException, HeadlessException,
AWTException
{
driver.get(baseUrl + "admin/");
driver.findElement(By.linkText("Compiere Web Application Login")).click();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
String data[][]=null;
data=DataDriven.readDataToExcelFile("src/Config/login.xls",0);
driver.findElement(By.name(ObjectRep.loginUserName)).clear();
driver.findElement(By.name(ObjectRep.loginUserName)).sendKeys(data[0][0]);
driver.findElement(By.name(ObjectRep.loginPassword)).clear();
driver.findElement(By.name(ObjectRep.loginPassword)).sendKeys(data[0][1]);
driver.findElement(By.id(ObjectRep.loginOkButton)).click();
// Select Role
driver.findElement(By.xpath(ObjectRep.loginRole)).clear();
driver.findElement(By.xpath(ObjectRep.loginRole)).sendKeys(data[0][2]);
//Cake World AdminRole
driver.findElement(By.xpath(ObjectRep.loginDate)).clear();
driver.findElement(By.xpath(ObjectRep.loginDate)).sendKeys(data[0][3]);
driver.findElement(By.id(ObjectRep.loginOkButton)).click();
WebElement myDynamicElement = (new WebDriverWait(driver, 60)).until(new
ExpectedCondition<WebElement>(){
@Override
public WebElement apply(WebDriver d) {
return d.findElement(By.id(ObjectRep.loginHome));
}});
// ScreenShot.takeScreenShot(driver, "screenshot.jpg");
return 0;
}
}
TestLogin.java
public void productbeforetrx(WebDriver driver, String pricelist,
String warehouse, ArrayList<String> productList) {
driver.findElement(By.xpath("//td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr/td[2]/div")).click(
);
driver.findElement(By.xpath("//td[3]/table/tbody/tr/td[2]/div")).click();
// driver.findElement(By.xpath("//td[3]/table/tbody/tr/td[2]/div/div")).click();
driver.findElement(By.xpath("//div/div/table/tbody/tr[8]/td")).click();
// Search Product.
driver.findElement(By.xpath("//tr[2]/td[6]/table/tbody/tr/td/input")).clear();
driver.findElement(By.xpath("//tr[2]/td[6]/table/tbody/tr/td/input")).sendKeys(pricelist);
driver.findElement(By.xpath("//tr[2]/td[4]/table/tbody/tr/td/input")).clear();
driver.findElement(By.xpath("//tr[2]/td[4]/table/tbody/tr/td/input")).sendKeys(warehouse);
// Get all the product qty before Transaction
for (int i = 0; i < productList.size(); i++) {
driver.findElement(
By.xpath("//tr[2]/td/table/tbody/tr/td/table/tbody/tr[2]/td/table/tbody/tr/td[2]/input"))
.clear();
driver.findElement(
By.xpath("//tr[2]/td/table/tbody/tr/td/table/tbody/tr[2]/td/table/tbody/tr/td[2]/input"))
.sendKeys(productList.get(i));
driver.findElement(By.xpath("//tr[3]/td[2]/button")).click();
// wait for qty values load
new WebDriverWait(driver, 60)
.until(new ExpectedCondition<WebElement>() {
@Override
public WebElement apply(WebDriver d) {
return d.findElement(By.xpath("//tr[3]/td[8]"));
}
});
String avail_qty = driver.findElement(By.xpath("//tr[3]/td[8]"))
.getText();
String onhand_qty = driver.findElement(By.xpath("//tr[3]/td[12]"))
.getText();
String reserve_qty = driver.findElement(By.xpath("//tr[3]/td[13]"))
.getText();
String order_qty = driver.findElement(By.xpath("//tr[3]/td[14]"))
.getText();
// Replace comma in string qty and convert into double
avail_qty_btrx.add(i,Double.parseDouble(avail_qty.replace(",", "")));
onhand_qty_btrx.add(i,Double.parseDouble(onhand_qty.replace(",", "")));
rever_qty_btrx.add(i,Double.parseDouble(reserve_qty.replace(",", "")));
order_qty_btrx.add(i,Double.parseDouble(order_qty.replace(",", "")));
}
driver.findElement(By.xpath("//div/table/tbody/tr/td[2]/div/div"))
.click();
}
4) Utils package in src
It contains the java classes for
 Fetching the data from test data sheet
 Fetching the object property test data
 Other functionality.
Data Driven.java
package Utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.ss.usermodel.Cell;
public class DataDriven {
private static Logger log = Logger.getLogger("DataDriven.class");
public static String[][] readDataToExcelFile(String e_WorkBook,int e_sheet) throws IOException {
File f1 = new File(e_WorkBook);
String path = f1.getAbsolutePath();
String format = null;
Double d;
String[][] data = null;
int totalRows, totalColumns;
try
{
FileInputStream fis = new FileInputStream(path);
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(e_sheet);
totalRows = sheet.getPhysicalNumberOfRows();
HSSFRow row = sheet.getRow(0);
totalColumns = row.getPhysicalNumberOfCells();
int cellType = 0;
data = new String[totalRows-1][totalColumns];
for (int rowNum = 1; rowNum < totalRows; rowNum++) {
for (int cellNum = 0; cellNum < totalColumns; cellNum++) {
HSSFCell cell = sheet.getRow(rowNum).getCell(cellNum);
format = cell.getCellStyle().getDataFormatString();
cellType = cell.getCellType();
if (format.equals("General")) {
if (cellType == Cell.CELL_TYPE_STRING)
{
data[rowNum-1][cellNum] = cell.getStringCellValue();
} else if (cellType == Cell.CELL_TYPE_NUMERIC)
{
d = cell.getNumericCellValue();
data[rowNum-1][cellNum] = d.toString();
}
} else if (format.equals("dd/mm/yyyy")) {
java.util.Date value = cell.getDateCellValue();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
data[rowNum-1][cellNum] = df.format(value);
} else if (format.equals("#,##0.00")) {
NumberFormat numberFormatter = new
DecimalFormat("#,##0.00");
d = cell.getNumericCellValue();
data[rowNum-1][cellNum] = numberFormatter.format(d);
}
}
}
fis.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return data;
}
}
ObjectRep.java
package Utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.apache.log4j.Logger;
public class ObjectRep {
//Property file parameters
private FileInputStream inStream;
private File propertyFile;
private Properties property;
public static String path = null;
private String p_URL = "URL";
private String p_LoginUserName = "LOGIN.USERNAME";
private String p_LoginPassword = "LOGIN.PASSWORD";
private String p_LoginRole = "LOGIN.ROLE";
private String p_LoginDate = "LOGIN.DATE";
private String p_LoginOkButton = "LOGIN.OKBUTTON";
private String p_LoginHome = "LOGIN.HOME";
//Connection parameters
public static String url = null;
public static String loginUserName = null;
public static String loginPassword = null;
public static String loginRole = null;
public static String loginDate = null;
public static String loginOkButton = null;
public static String loginHome = null;
//Database connenction parameter
//Logging
private static Logger log = Logger.getLogger("ObjectRep.class");
public void objectRefer(String o_PropertyFile) throws IOException
{
try {
File f1 = new File(o_PropertyFile);
path = f1.getAbsolutePath();
// path=FilenameUtils.separatorsToSystem(path);
// String fileSep = System.getProperty("file.separator");
// if(fileSep.equals(""))
// path=path.replace("", "")
propertyFile = new File(path);
property = new Properties();
//Read info from propertyFile
inStream = new FileInputStream(propertyFile);
//Load info from fileInputStream
property.load(inStream);
url = property.getProperty(p_URL);
loginUserName = property.getProperty(p_LoginUserName);
loginPassword = property.getProperty(p_LoginPassword);
loginRole = property.getProperty(p_LoginRole);
loginDate = property.getProperty(p_LoginDate);
loginOkButton = property.getProperty(p_LoginOkButton);
loginHome=property.getProperty(p_LoginHome);
} catch (IOException e) {
log.error("Unable to read ObjectRep File"+e.getMessage());
} finally {
try {
inStream.close();
propertyFile = null;
} catch (Exception e) {
inStream = null;
propertyFile = null;
}
}
log.info("Objects read for object repository successfully.");
}// createConnection
}
ScreenShot.java
package Utils;
import java.awt.AWTException;
import java.awt.HeadlessException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import javax.imageio.ImageIO;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.OutputType;
public class ScreenShot {
public static void takeScreenShot(WebDriver driver,String filename) throws IOException,
HeadlessException, AWTException
{
File f1 = new File("src/ScreenShots");
String path = f1.getAbsolutePath();
BufferedImage image = new Robot().createScreenCapture(new
Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
ImageIO.write(image, "png", new File(path + "//" + filename));
// File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// copyFile(scrFile, new File(path + "//" + filename));
}
public static void copyFile(File in, File out) throws IOException
{
FileChannel inChannel = new FileInputStream(in).getChannel();
FileChannel outChannel = new FileOutputStream(out).getChannel();
try {
inChannel.transferTo(0, inChannel.size(),outChannel);
}
catch (IOException e) {
throw e;
}
finally {
if (inChannel != null) inChannel.close();
if (outChannel != null) outChannel.close();
}
}
}
5) log4j.xml – Configure file for log 4j
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<!-- ===================================================================== -->
<!-- -->
<!-- Log4j Configuration -->
<!-- -->
<!-- ===================================================================== -->
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
<!-- ================================= -->
<!-- Preserve messages in a local file -->
<!-- ================================= -->
<!-- A time/date based rolling appender -->
<appender name="SELENIUMAUTOMATION" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="SeleniumLog.log"/>
<param name="Append" value="false"/>
<!-- Rollover at midnight each day -->
<param name="DatePattern" value="'.'yyyy-MM-dd"/>
<!-- Rollover at the top of each hour
<param name="DatePattern" value="'.'yyyy-MM-dd-HH"/>
-->
<layout class="org.apache.log4j.PatternLayout">
<!-- The default pattern: Date Priority [Category] Messagen -->
<param name="ConversionPattern" value="%d %-5p [%c] %m%n"/>
<!-- The full pattern: Date MS Priority [Category] (Thread:NDC) Messagen
<param name="ConversionPattern" value="%d %-5r %-5p [%c] (%t:%x) %m%n"/>
-->
</layout>
</appender>
<!-- ======================= -->
<!-- Setup the Root category -->
<!-- ======================= -->
<root>
<priority value="INFO" />
<appender-ref ref="SELENIUMAUTOMATION"/>
</root>
</log4j:configuration>
6) Final.xml – xml to run the automation script.
<?xml version="1.0" encoding="UTF-8"?>
<suite name="Compiere38" verbose="10">
<parameter name="selenium.host" value="localhost" />
<parameter name="selenium.port" value="4444" />
<parameter name="selenium.browser" value="*firefox" />
<parameter name="selenium.url" value="http://192.168.0.87:8080/" />
<test name="Login" preserve-order="true">
<classes>
<class name="testApps.TestLogin">
<methods>
<include name="relation" />
</methods>
</class>
</classes>
</test>
</suite>
7) Build folder - Created by build.xml
<?xml version="1.0" encoding="UTF-8"?>
<project name="Compiere38SmokeTest" default="TestReport" basedir=".">
<property name ="build.dir" value="${basedir}/build"/>
<property name="lib.dir" value="${basedir}/libs"/>
<property name="src.dir" value="${basedir}/src"/>
<property name="name" value="value"/>
<!-- <property name="browser" location="C:/Program Files/Mozilla
Firefox/Firefox.exe"/>
<property name="file" location="${basedir}/testng-xslt/index.html"/>
-->
<target name="setClassPath">
<echo message="Im in set Class"/>
<path id="classpath_jars">
<path id="${basedir}/"/>
<fileset dir="${lib.dir}" includes="*.jar"/>
</path>
<pathconvert pathsep=":" property="test.classpath"
refid="classpath_jars"/>
</target>
<target name="loadTestNG">
<taskdef resource="testngtasks" classpath="${test.classpath}"/>
</target>
<target name="init">
<mkdir dir="${build.dir}"/>
</target>
<target name="clean">
<echo message="deleting existing build directory"/>
<delete dir="${build.dir}"/>
</target>
<target name="compile" >
<echo message="classpath: ${test.classpath}"/>
<echo message="compiling..."/>
<javac destdir="${build.dir}" srcdir="${src.dir}" classpath="$
{test.classpath}" encoding="cp1252"/>
</target>
<target name="run" >
<testng classpath ="${test.classpath}:${build.dir}">
<xmlfileset dir="${basedir}" includes="Final.xml"/>
</testng>
</target>
<target name="TestReport" depends="setClassPath, loadTestNG, clean,
init, compile, run">
<delete dir="${basedir}/testng-xslt">
</delete>
<mkdir dir="${basedir}/testng-xslt">
</mkdir>
<xslt in="${basedir}test-outputtestng-results.xml" style="$
{basedir}/testng-results.xsl" out="${basedir}/testng-xslt/index.html">
<param expression="${basedir}/testng-xslt/"
name="testNgXslt.outputDir" />
<param expression="true" name="testNgXslt.sortTestCaseLinks"
/>
<param expression="FAIL,SKIP,PASS,CONF,BY_CLASS"
name="testNgXslt.testDetailsFilter" />
<param expression="true" name="testNgXslt.showRuntimeTotals"
/>
<classpath refid="classpath_jars">
</classpath>
</xslt>
<!-- <exec executable="${browser}" spawn="true">
<arg value="${file}"/>
</exec> -->
</target>
</project>
8) test-output folder
Created for every testNG execution. We get see the report by clicking the index.html in test-output
9) testng-xslt folder
Created from testing-results.xml in test-output folder for every testNG execution. We get see the report
by clicking the index.html in the testing-xslt folder.
10) SeleniumLog.log
Created/appended for the for every testNG execution and writes the log.

More Related Content

What's hot (18)

PDF
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
Nicolas Bettenburg
 
PDF
ERRest in Depth
WO Community
 
DOCX
201913046 wahyu septiansyah network programing
wahyuseptiansyah
 
PPTX
The uniform interface is 42
Yevhen Bobrov
 
PDF
ERRest - Designing a good REST service
WO Community
 
DOCX
Code red SUM
Shumail Haider
 
PDF
OQL querying and indexes with Apache Geode (incubating)
Jason Huynh
 
PDF
Advanced java practical semester 6_computer science
Niraj Bharambe
 
PDF
No SQL Unit - Devoxx 2012
Alex Soto
 
PDF
Spock
Naiyer Asif
 
PPTX
Тарас Олексин - Sculpt! Your! Tests!
DataArt
 
PDF
Struts2 - 101
Munish Gupta
 
PDF
MarsJUG - Une nouvelle vision des tests avec Arquillian
Alexis Hassler
 
PPTX
บทที่ 4 การเพิ่มข้อมูลลงฐานข้อมูล
Priew Chakrit
 
PDF
Teste de Integração com DbUnit e jIntegrity
Washington Botelho
 
PDF
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
PDF
The Ring programming language version 1.10 book - Part 37 of 212
Mahmoud Samir Fayed
 
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
Nicolas Bettenburg
 
ERRest in Depth
WO Community
 
201913046 wahyu septiansyah network programing
wahyuseptiansyah
 
The uniform interface is 42
Yevhen Bobrov
 
ERRest - Designing a good REST service
WO Community
 
Code red SUM
Shumail Haider
 
OQL querying and indexes with Apache Geode (incubating)
Jason Huynh
 
Advanced java practical semester 6_computer science
Niraj Bharambe
 
No SQL Unit - Devoxx 2012
Alex Soto
 
Тарас Олексин - Sculpt! Your! Tests!
DataArt
 
Struts2 - 101
Munish Gupta
 
MarsJUG - Une nouvelle vision des tests avec Arquillian
Alexis Hassler
 
บทที่ 4 การเพิ่มข้อมูลลงฐานข้อมูล
Priew Chakrit
 
Teste de Integração com DbUnit e jIntegrity
Washington Botelho
 
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
The Ring programming language version 1.10 book - Part 37 of 212
Mahmoud Samir Fayed
 

Similar to Selenium Webdriver with data driven framework (10)

TXT
Excelsheet
amarnathprasad
 
PPTX
Roman iovlev. Test UI with JDI - Selenium camp
Роман Иовлев
 
PDF
Data Driven Framework In Selenium Webdriver | Data Driven Testing | Selenium ...
Edureka!
 
PDF
Page Object Model and Implementation in Selenium
Zoe Gilbert
 
PPTX
Роман Иовлев «Open Source UI Automation Tests on C#»
SpbDotNet Community
 
PDF
Data Driven Framework in Selenium
Knoldus Inc.
 
PDF
APPLICATION TO DOCUMENT ALL THE DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
DEEPANSHU GUPTA
 
PDF
Selenium cheat sheet
Sri Priya P Kulkarni
 
PDF
Selenium Openhouse CP-SAT - Handling Dynamic Web Tables
Agile Testing Alliance
 
PPTX
Future of UI Automation testing and JDI
COMAQA.BY
 
Excelsheet
amarnathprasad
 
Roman iovlev. Test UI with JDI - Selenium camp
Роман Иовлев
 
Data Driven Framework In Selenium Webdriver | Data Driven Testing | Selenium ...
Edureka!
 
Page Object Model and Implementation in Selenium
Zoe Gilbert
 
Роман Иовлев «Open Source UI Automation Tests on C#»
SpbDotNet Community
 
Data Driven Framework in Selenium
Knoldus Inc.
 
APPLICATION TO DOCUMENT ALL THE DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
DEEPANSHU GUPTA
 
Selenium cheat sheet
Sri Priya P Kulkarni
 
Selenium Openhouse CP-SAT - Handling Dynamic Web Tables
Agile Testing Alliance
 
Future of UI Automation testing and JDI
COMAQA.BY
 
Ad

Recently uploaded (20)

PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PPTX
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PPTX
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PPTX
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
PDF
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
Ad

Selenium Webdriver with data driven framework

  • 1. Selenium Webdriver with Data Driven Framework Data Driven Framework:  Externalized the data from the scripts.  Framework will function based on the number of combination of test data available in external files.  Scripts should not be modified for any addition of test case or scenario if the transaction or action (and the navigation involved in the transaction) remains same. In this example for compiere 3.8.0 login contains  Config and ScreenShots folders in src folder - Contains test and configure data file  testApps and Utils packages in src – Contains java classes for functional testing.  log4j.xml - Configure file for log 4j  build.xml – To build the automation source.  Final.xml – xml to run the automation script.  Build folder - Created by build.xml  test-output folder - Created for every testNG execution  testng-xslt - Created from testing-results.xml in test-output folder for every testNG execution.  SeleniumLog.log - Created/appended for the for every testNG execution and writes the log.
  • 2. 1) Config folder in src folder It contains the object repository property and test data sheet for the test.
  • 3. Login.Xls (Test Data) ObjectRep.Property file #URL URL = http://192.168.0.87:8080/ #Login Screen Objects LOGIN.USERNAME = 0|0|User LOGIN.PASSWORD = 0|0|Password LOGIN.ROLE = //input[@name='0|0|AD_Role_ID'] LOGIN.DATE = //tr[5]/td[2]/table/tbody/tr/td/input LOGIN.OKBUTTON = 0|0|Ok LOGIN.HOME = WindowName 2) ScreenShots folders in src folder It contains the screenshot taken it the test execution for every test cases.
  • 4. 3) testApps package in src It contains the java classes for functional testing (test script).
  • 5. Login.java package testApps; import java.awt.AWTException; import java.awt.HeadlessException; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; import Utils.ScreenShot; import Utils.ObjectRep; import Utils.DataDriven; public class Login { public int homePage(WebDriver driver,String baseUrl) throws IOException, HeadlessException, AWTException {
  • 6. driver.get(baseUrl + "admin/"); driver.findElement(By.linkText("Compiere Web Application Login")).click(); driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); String data[][]=null; data=DataDriven.readDataToExcelFile("src/Config/login.xls",0); driver.findElement(By.name(ObjectRep.loginUserName)).clear(); driver.findElement(By.name(ObjectRep.loginUserName)).sendKeys(data[0][0]); driver.findElement(By.name(ObjectRep.loginPassword)).clear(); driver.findElement(By.name(ObjectRep.loginPassword)).sendKeys(data[0][1]); driver.findElement(By.id(ObjectRep.loginOkButton)).click(); // Select Role driver.findElement(By.xpath(ObjectRep.loginRole)).clear(); driver.findElement(By.xpath(ObjectRep.loginRole)).sendKeys(data[0][2]); //Cake World AdminRole driver.findElement(By.xpath(ObjectRep.loginDate)).clear(); driver.findElement(By.xpath(ObjectRep.loginDate)).sendKeys(data[0][3]); driver.findElement(By.id(ObjectRep.loginOkButton)).click(); WebElement myDynamicElement = (new WebDriverWait(driver, 60)).until(new ExpectedCondition<WebElement>(){ @Override public WebElement apply(WebDriver d) { return d.findElement(By.id(ObjectRep.loginHome)); }}); // ScreenShot.takeScreenShot(driver, "screenshot.jpg"); return 0; } } TestLogin.java public void productbeforetrx(WebDriver driver, String pricelist, String warehouse, ArrayList<String> productList) { driver.findElement(By.xpath("//td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr/td[2]/div")).click( ); driver.findElement(By.xpath("//td[3]/table/tbody/tr/td[2]/div")).click(); // driver.findElement(By.xpath("//td[3]/table/tbody/tr/td[2]/div/div")).click(); driver.findElement(By.xpath("//div/div/table/tbody/tr[8]/td")).click(); // Search Product. driver.findElement(By.xpath("//tr[2]/td[6]/table/tbody/tr/td/input")).clear(); driver.findElement(By.xpath("//tr[2]/td[6]/table/tbody/tr/td/input")).sendKeys(pricelist); driver.findElement(By.xpath("//tr[2]/td[4]/table/tbody/tr/td/input")).clear(); driver.findElement(By.xpath("//tr[2]/td[4]/table/tbody/tr/td/input")).sendKeys(warehouse);
  • 7. // Get all the product qty before Transaction for (int i = 0; i < productList.size(); i++) { driver.findElement( By.xpath("//tr[2]/td/table/tbody/tr/td/table/tbody/tr[2]/td/table/tbody/tr/td[2]/input")) .clear(); driver.findElement( By.xpath("//tr[2]/td/table/tbody/tr/td/table/tbody/tr[2]/td/table/tbody/tr/td[2]/input")) .sendKeys(productList.get(i)); driver.findElement(By.xpath("//tr[3]/td[2]/button")).click(); // wait for qty values load new WebDriverWait(driver, 60) .until(new ExpectedCondition<WebElement>() { @Override public WebElement apply(WebDriver d) { return d.findElement(By.xpath("//tr[3]/td[8]")); } }); String avail_qty = driver.findElement(By.xpath("//tr[3]/td[8]")) .getText(); String onhand_qty = driver.findElement(By.xpath("//tr[3]/td[12]")) .getText(); String reserve_qty = driver.findElement(By.xpath("//tr[3]/td[13]")) .getText(); String order_qty = driver.findElement(By.xpath("//tr[3]/td[14]")) .getText(); // Replace comma in string qty and convert into double avail_qty_btrx.add(i,Double.parseDouble(avail_qty.replace(",", ""))); onhand_qty_btrx.add(i,Double.parseDouble(onhand_qty.replace(",", ""))); rever_qty_btrx.add(i,Double.parseDouble(reserve_qty.replace(",", ""))); order_qty_btrx.add(i,Double.parseDouble(order_qty.replace(",", ""))); } driver.findElement(By.xpath("//div/table/tbody/tr/td[2]/div/div")) .click(); } 4) Utils package in src It contains the java classes for  Fetching the data from test data sheet  Fetching the object property test data  Other functionality.
  • 8. Data Driven.java package Utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.sql.Date; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import org.apache.log4j.Logger; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.ss.usermodel.Cell;
  • 9. public class DataDriven { private static Logger log = Logger.getLogger("DataDriven.class"); public static String[][] readDataToExcelFile(String e_WorkBook,int e_sheet) throws IOException { File f1 = new File(e_WorkBook); String path = f1.getAbsolutePath(); String format = null; Double d; String[][] data = null; int totalRows, totalColumns; try { FileInputStream fis = new FileInputStream(path); HSSFWorkbook workbook = new HSSFWorkbook(fis); HSSFSheet sheet = workbook.getSheetAt(e_sheet); totalRows = sheet.getPhysicalNumberOfRows(); HSSFRow row = sheet.getRow(0); totalColumns = row.getPhysicalNumberOfCells(); int cellType = 0; data = new String[totalRows-1][totalColumns]; for (int rowNum = 1; rowNum < totalRows; rowNum++) { for (int cellNum = 0; cellNum < totalColumns; cellNum++) { HSSFCell cell = sheet.getRow(rowNum).getCell(cellNum); format = cell.getCellStyle().getDataFormatString(); cellType = cell.getCellType(); if (format.equals("General")) { if (cellType == Cell.CELL_TYPE_STRING) { data[rowNum-1][cellNum] = cell.getStringCellValue(); } else if (cellType == Cell.CELL_TYPE_NUMERIC) { d = cell.getNumericCellValue(); data[rowNum-1][cellNum] = d.toString(); } } else if (format.equals("dd/mm/yyyy")) { java.util.Date value = cell.getDateCellValue(); DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); data[rowNum-1][cellNum] = df.format(value); } else if (format.equals("#,##0.00")) { NumberFormat numberFormatter = new DecimalFormat("#,##0.00"); d = cell.getNumericCellValue(); data[rowNum-1][cellNum] = numberFormatter.format(d); } } } fis.close();
  • 10. } catch(Exception e) { e.printStackTrace(); } return data; } } ObjectRep.java package Utils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; import org.apache.log4j.Logger; public class ObjectRep { //Property file parameters private FileInputStream inStream; private File propertyFile; private Properties property; public static String path = null; private String p_URL = "URL"; private String p_LoginUserName = "LOGIN.USERNAME"; private String p_LoginPassword = "LOGIN.PASSWORD"; private String p_LoginRole = "LOGIN.ROLE"; private String p_LoginDate = "LOGIN.DATE"; private String p_LoginOkButton = "LOGIN.OKBUTTON"; private String p_LoginHome = "LOGIN.HOME"; //Connection parameters public static String url = null; public static String loginUserName = null; public static String loginPassword = null; public static String loginRole = null; public static String loginDate = null; public static String loginOkButton = null; public static String loginHome = null; //Database connenction parameter //Logging private static Logger log = Logger.getLogger("ObjectRep.class");
  • 11. public void objectRefer(String o_PropertyFile) throws IOException { try { File f1 = new File(o_PropertyFile); path = f1.getAbsolutePath(); // path=FilenameUtils.separatorsToSystem(path); // String fileSep = System.getProperty("file.separator"); // if(fileSep.equals("")) // path=path.replace("", "") propertyFile = new File(path); property = new Properties(); //Read info from propertyFile inStream = new FileInputStream(propertyFile); //Load info from fileInputStream property.load(inStream); url = property.getProperty(p_URL); loginUserName = property.getProperty(p_LoginUserName); loginPassword = property.getProperty(p_LoginPassword); loginRole = property.getProperty(p_LoginRole); loginDate = property.getProperty(p_LoginDate); loginOkButton = property.getProperty(p_LoginOkButton); loginHome=property.getProperty(p_LoginHome); } catch (IOException e) { log.error("Unable to read ObjectRep File"+e.getMessage()); } finally { try { inStream.close(); propertyFile = null; } catch (Exception e) { inStream = null; propertyFile = null; } } log.info("Objects read for object repository successfully."); }// createConnection } ScreenShot.java package Utils; import java.awt.AWTException;
  • 12. import java.awt.HeadlessException; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; import javax.imageio.ImageIO; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.OutputType; public class ScreenShot { public static void takeScreenShot(WebDriver driver,String filename) throws IOException, HeadlessException, AWTException { File f1 = new File("src/ScreenShots"); String path = f1.getAbsolutePath(); BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize())); ImageIO.write(image, "png", new File(path + "//" + filename)); // File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); // copyFile(scrFile, new File(path + "//" + filename)); } public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(),outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } }
  • 13. 5) log4j.xml – Configure file for log 4j <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <!-- ===================================================================== --> <!-- --> <!-- Log4j Configuration --> <!-- --> <!-- ===================================================================== --> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false"> <!-- ================================= --> <!-- Preserve messages in a local file --> <!-- ================================= --> <!-- A time/date based rolling appender --> <appender name="SELENIUMAUTOMATION" class="org.apache.log4j.DailyRollingFileAppender"> <param name="File" value="SeleniumLog.log"/> <param name="Append" value="false"/> <!-- Rollover at midnight each day --> <param name="DatePattern" value="'.'yyyy-MM-dd"/> <!-- Rollover at the top of each hour <param name="DatePattern" value="'.'yyyy-MM-dd-HH"/> --> <layout class="org.apache.log4j.PatternLayout"> <!-- The default pattern: Date Priority [Category] Messagen --> <param name="ConversionPattern" value="%d %-5p [%c] %m%n"/> <!-- The full pattern: Date MS Priority [Category] (Thread:NDC) Messagen <param name="ConversionPattern" value="%d %-5r %-5p [%c] (%t:%x) %m%n"/> --> </layout> </appender> <!-- ======================= --> <!-- Setup the Root category --> <!-- ======================= --> <root> <priority value="INFO" /> <appender-ref ref="SELENIUMAUTOMATION"/>
  • 14. </root> </log4j:configuration> 6) Final.xml – xml to run the automation script. <?xml version="1.0" encoding="UTF-8"?> <suite name="Compiere38" verbose="10"> <parameter name="selenium.host" value="localhost" /> <parameter name="selenium.port" value="4444" /> <parameter name="selenium.browser" value="*firefox" /> <parameter name="selenium.url" value="http://192.168.0.87:8080/" /> <test name="Login" preserve-order="true"> <classes> <class name="testApps.TestLogin"> <methods> <include name="relation" /> </methods> </class> </classes> </test> </suite> 7) Build folder - Created by build.xml <?xml version="1.0" encoding="UTF-8"?> <project name="Compiere38SmokeTest" default="TestReport" basedir="."> <property name ="build.dir" value="${basedir}/build"/> <property name="lib.dir" value="${basedir}/libs"/> <property name="src.dir" value="${basedir}/src"/> <property name="name" value="value"/> <!-- <property name="browser" location="C:/Program Files/Mozilla Firefox/Firefox.exe"/> <property name="file" location="${basedir}/testng-xslt/index.html"/> --> <target name="setClassPath"> <echo message="Im in set Class"/> <path id="classpath_jars"> <path id="${basedir}/"/> <fileset dir="${lib.dir}" includes="*.jar"/> </path> <pathconvert pathsep=":" property="test.classpath" refid="classpath_jars"/> </target> <target name="loadTestNG"> <taskdef resource="testngtasks" classpath="${test.classpath}"/> </target> <target name="init"> <mkdir dir="${build.dir}"/> </target> <target name="clean">
  • 15. <echo message="deleting existing build directory"/> <delete dir="${build.dir}"/> </target> <target name="compile" > <echo message="classpath: ${test.classpath}"/> <echo message="compiling..."/> <javac destdir="${build.dir}" srcdir="${src.dir}" classpath="$ {test.classpath}" encoding="cp1252"/> </target> <target name="run" > <testng classpath ="${test.classpath}:${build.dir}"> <xmlfileset dir="${basedir}" includes="Final.xml"/> </testng> </target> <target name="TestReport" depends="setClassPath, loadTestNG, clean, init, compile, run"> <delete dir="${basedir}/testng-xslt"> </delete> <mkdir dir="${basedir}/testng-xslt"> </mkdir> <xslt in="${basedir}test-outputtestng-results.xml" style="$ {basedir}/testng-results.xsl" out="${basedir}/testng-xslt/index.html"> <param expression="${basedir}/testng-xslt/" name="testNgXslt.outputDir" /> <param expression="true" name="testNgXslt.sortTestCaseLinks" /> <param expression="FAIL,SKIP,PASS,CONF,BY_CLASS" name="testNgXslt.testDetailsFilter" /> <param expression="true" name="testNgXslt.showRuntimeTotals" /> <classpath refid="classpath_jars"> </classpath> </xslt> <!-- <exec executable="${browser}" spawn="true"> <arg value="${file}"/> </exec> --> </target> </project> 8) test-output folder Created for every testNG execution. We get see the report by clicking the index.html in test-output
  • 16. 9) testng-xslt folder Created from testing-results.xml in test-output folder for every testNG execution. We get see the report by clicking the index.html in the testing-xslt folder.
  • 17. 10) SeleniumLog.log Created/appended for the for every testNG execution and writes the log.