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

PDF
Js 单元测试框架介绍
PPT
Wicket Security Presentation
PDF
Form認証で学ぶSpring Security入門
PDF
Architecture Components
PDF
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
PDF
spring-tutorial
PDF
Testdrevet javautvikling på objektorienterte skinner
PDF
ERRest
Js 单元测试框架介绍
Wicket Security Presentation
Form認証で学ぶSpring Security入門
Architecture Components
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
spring-tutorial
Testdrevet javautvikling på objektorienterte skinner
ERRest

What's hot (18)

PDF
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
PDF
ERRest in Depth
DOCX
201913046 wahyu septiansyah network programing
PPTX
The uniform interface is 42
PDF
ERRest - Designing a good REST service
DOCX
Code red SUM
PDF
OQL querying and indexes with Apache Geode (incubating)
PDF
Advanced java practical semester 6_computer science
PDF
No SQL Unit - Devoxx 2012
PDF
PPTX
Тарас Олексин - Sculpt! Your! Tests!
PDF
Struts2 - 101
PDF
MarsJUG - Une nouvelle vision des tests avec Arquillian
PPTX
บทที่ 4 การเพิ่มข้อมูลลงฐานข้อมูล
PDF
Teste de Integração com DbUnit e jIntegrity
PDF
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
PDF
The Ring programming language version 1.10 book - Part 37 of 212
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
ERRest in Depth
201913046 wahyu septiansyah network programing
The uniform interface is 42
ERRest - Designing a good REST service
Code red SUM
OQL querying and indexes with Apache Geode (incubating)
Advanced java practical semester 6_computer science
No SQL Unit - Devoxx 2012
Тарас Олексин - Sculpt! Your! Tests!
Struts2 - 101
MarsJUG - Une nouvelle vision des tests avec Arquillian
บทที่ 4 การเพิ่มข้อมูลลงฐานข้อมูล
Teste de Integração com DbUnit e jIntegrity
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
The Ring programming language version 1.10 book - Part 37 of 212
Ad

Similar to Selenium Webdriver with data driven framework (10)

TXT
Excelsheet
PPTX
Roman iovlev. Test UI with JDI - Selenium camp
PDF
Data Driven Framework In Selenium Webdriver | Data Driven Testing | Selenium ...
PDF
Page Object Model and Implementation in Selenium
PPTX
Роман Иовлев «Open Source UI Automation Tests on C#»
PDF
Data Driven Framework in Selenium
PDF
APPLICATION TO DOCUMENT ALL THE DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
PDF
Selenium cheat sheet
PDF
Selenium Openhouse CP-SAT - Handling Dynamic Web Tables
PPTX
Future of UI Automation testing and JDI
Excelsheet
Roman iovlev. Test UI with JDI - Selenium camp
Data Driven Framework In Selenium Webdriver | Data Driven Testing | Selenium ...
Page Object Model and Implementation in Selenium
Роман Иовлев «Open Source UI Automation Tests on C#»
Data Driven Framework in Selenium
APPLICATION TO DOCUMENT ALL THE DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
Selenium cheat sheet
Selenium Openhouse CP-SAT - Handling Dynamic Web Tables
Future of UI Automation testing and JDI
Ad

Recently uploaded (20)

PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
master seminar digital applications in india
PDF
Pre independence Education in Inndia.pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
01-Introduction-to-Information-Management.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PDF
Introduction-to-Social-Work-by-Leonora-Serafeca-De-Guzman-Group-2.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PPH.pptx obstetrics and gynecology in nursing
master seminar digital applications in india
Pre independence Education in Inndia.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
01-Introduction-to-Information-Management.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Introduction-to-Social-Work-by-Leonora-Serafeca-De-Guzman-Group-2.pdf
human mycosis Human fungal infections are called human mycosis..pptx
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
2.FourierTransform-ShortQuestionswithAnswers.pdf
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...

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.