Más contenido relacionado La actualidad más candente (18) Similar a Selenium Webdriver with data driven framework (20) Selenium Webdriver with data driven framework1. 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.