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)

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
Nicolas Bettenburg
 
ERRest in Depth
ERRest in DepthERRest in Depth
ERRest in Depth
WO Community
 
201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing
wahyuseptiansyah
 
The uniform interface is 42
The uniform interface is 42The uniform interface is 42
The uniform interface is 42
Yevhen Bobrov
 
ERRest - Designing a good REST service
ERRest - Designing a good REST serviceERRest - Designing a good REST service
ERRest - Designing a good REST service
WO Community
 
Code red SUM
Code red SUMCode red SUM
Code red SUM
Shumail Haider
 
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)
Jason Huynh
 
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
Niraj Bharambe
 
No SQL Unit - Devoxx 2012
No SQL Unit - Devoxx 2012No SQL Unit - Devoxx 2012
No SQL Unit - Devoxx 2012
Alex Soto
 
Spock
SpockSpock
Spock
Naiyer Asif
 
Тарас Олексин - Sculpt! Your! Tests!
Тарас Олексин  - Sculpt! Your! Tests!Тарас Олексин  - Sculpt! Your! Tests!
Тарас Олексин - Sculpt! Your! Tests!
DataArt
 
Struts2 - 101
Struts2 - 101Struts2 - 101
Struts2 - 101
Munish Gupta
 
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
Alexis Hassler
 
บทที่ 4 การเพิ่มข้อมูลลงฐานข้อมูล
บทที่ 4 การเพิ่มข้อมูลลงฐานข้อมูลบทที่ 4 การเพิ่มข้อมูลลงฐานข้อมูล
บทที่ 4 การเพิ่มข้อมูลลงฐานข้อมูล
Priew Chakrit
 
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
Washington Botelho
 
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
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
Mahmoud Samir Fayed
 
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
Nicolas Bettenburg
 
201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing
wahyuseptiansyah
 
The uniform interface is 42
The uniform interface is 42The uniform interface is 42
The uniform interface is 42
Yevhen Bobrov
 
ERRest - Designing a good REST service
ERRest - Designing a good REST serviceERRest - Designing a good REST service
ERRest - Designing a good REST service
WO Community
 
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)
Jason Huynh
 
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
Niraj Bharambe
 
No SQL Unit - Devoxx 2012
No SQL Unit - Devoxx 2012No SQL Unit - Devoxx 2012
No SQL Unit - Devoxx 2012
Alex Soto
 
Тарас Олексин - Sculpt! Your! Tests!
Тарас Олексин  - Sculpt! Your! Tests!Тарас Олексин  - Sculpt! Your! Tests!
Тарас Олексин - Sculpt! Your! Tests!
DataArt
 
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
Alexis Hassler
 
บทที่ 4 การเพิ่มข้อมูลลงฐานข้อมูล
บทที่ 4 การเพิ่มข้อมูลลงฐานข้อมูลบทที่ 4 การเพิ่มข้อมูลลงฐานข้อมูล
บทที่ 4 การเพิ่มข้อมูลลงฐานข้อมูล
Priew Chakrit
 
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
Washington Botelho
 
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
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
Mahmoud Samir Fayed
 

Similar to 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
Artem Nagornyi
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unit
liminescence
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
javatwo2011
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
Suman Sourav
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
Divakar Gu
 
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
 
Java and SPARQL
Java and SPARQLJava and SPARQL
Java and SPARQL
Raji Ghawi
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
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
jeresig
 
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
caswenson
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
jeresig
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
Марія Русин
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
Zianed Hou
 
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
 
Data-Driven Unit Testing for Java
Data-Driven Unit Testing for JavaData-Driven Unit Testing for Java
Data-Driven Unit Testing for Java
Denilson Nastacio
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developers
Anton Udovychenko
 
Xml & Java
Xml & JavaXml & Java
Xml & Java
Slim Ouertani
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
Ivano Malavolta
 
Selenium interview questions and answers
Selenium interview questions and answersSelenium interview questions and answers
Selenium interview questions and answers
kavinilavuG
 
Dropwizard
DropwizardDropwizard
Dropwizard
Scott Leberknight
 
Web UI test automation instruments
Web UI test automation instrumentsWeb UI test automation instruments
Web UI test automation instruments
Artem Nagornyi
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unit
liminescence
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
javatwo2011
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
Divakar Gu
 
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
 
Java and SPARQL
Java and SPARQLJava and SPARQL
Java and SPARQL
Raji Ghawi
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
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
jeresig
 
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
caswenson
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
jeresig
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
Zianed Hou
 
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
 
Data-Driven Unit Testing for Java
Data-Driven Unit Testing for JavaData-Driven Unit Testing for Java
Data-Driven Unit Testing for Java
Denilson Nastacio
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developers
Anton Udovychenko
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
Ivano Malavolta
 
Selenium interview questions and answers
Selenium interview questions and answersSelenium interview questions and answers
Selenium interview questions and answers
kavinilavuG
 
Ad

Recently uploaded (20)

Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptxRai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
National Information Standards Organization (NISO)
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
Quiz Club of PSG College of Arts & Science
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
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.