SlideShare una empresa de Scribd logo
1 de 17
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.

Más contenido relacionado

La actualidad más candente

บทที่ 4 การเพิ่มข้อมูลลงฐานข้อมูล
บทที่ 4 การเพิ่มข้อมูลลงฐานข้อมูลบทที่ 4 การเพิ่มข้อมูลลงฐานข้อมูล
บทที่ 4 การเพิ่มข้อมูลลงฐานข้อมูล
Priew Chakrit
 

La actualidad más candente (18)

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

Similar a Selenium Webdriver with data driven framework

Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Lohika_Odessa_TechTalks
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 

Similar a Selenium Webdriver with data driven framework (20)

Web UI test automation instruments
Web UI test automation instrumentsWeb UI test automation instruments
Web UI test automation instruments
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unit
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
 
Java and SPARQL
Java and SPARQLJava and SPARQL
Java and SPARQL
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4
 
Learning Java 4 – Swing, SQL, and Security API
Learning Java 4 – Swing, SQL, and Security APILearning Java 4 – Swing, SQL, and Security API
Learning Java 4 – Swing, SQL, and Security API
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Data-Driven Unit Testing for Java
Data-Driven Unit Testing for JavaData-Driven Unit Testing for Java
Data-Driven Unit Testing for Java
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developers
 
Xml & Java
Xml & JavaXml & Java
Xml & Java
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
 
Selenium interview questions and answers
Selenium interview questions and answersSelenium interview questions and answers
Selenium interview questions and answers
 
Dropwizard
DropwizardDropwizard
Dropwizard
 

Último

Último (20)

Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 

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.