Keyword Driven Framework in Selenium....

Package Structure :
================

                             
                                                                                                                                                                                                                                                                                                                                          

























 objects.properites (This file will contain all the necessary information like url and the locators)
==========================================================================


















log4j.properties (To Create log file)
============================








ExcelReader.java (Class file to read data from Excel)
=========================================

 package excelInputAndOutput;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;

public class ExcelInteraction {

Workbook workbook;
FileInputStream inputstream;
public Sheet readExcel(String filePath,String fileName) throws IOException{
File file = new File(filePath+"\\"+fileName);
inputstream = new FileInputStream(file);
String fileExtensionName = fileName.substring(fileName.indexOf("."));
if(fileExtensionName.equals(".xlsx")){
workbook = new XSSFWorkbook(inputstream);
}else if(fileExtensionName.equals(".xls")){
workbook = new HSSFWorkbook(inputstream);
}

Sheet sheet = workbook.getSheet("TestData");


return sheet;

}

public void generateReport(File file) throws IOException{
FileOutputStream outputStream = new FileOutputStream(file);
workbook.write(outputStream);
outputStream.close();
}

public void closeInputStream() throws IOException{
inputstream.close();
}
public void closeExcel() throws IOException{
workbook.close();

}

public CellStyle customizeCell(String status){
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
style.setBorderBottom(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);

if(status.equals("Pass")){

         
style.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
           
   
}else if(status.equals("Fail")){

style.setFillForegroundColor(IndexedColors.RED.getIndex());
     style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
           
}

return style;

}

}

ReadObject.java (Class File to read properties from objects.properties)
====================================================
package operation;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class ReadObject {
Properties p = new Properties();
public Properties getObjectRepository() throws FileNotFoundException,IOException {
FileInputStream stream = new FileInputStream(new File(System.getProperty("user.dir")+"\\src\\objects.properties"));
p.load(stream);
return p;
}
}

UIOperation.java (Class File to do all the UI operations)
=========================================

package operation;

import java.util.Properties;

import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;

public class UIOperation {
WebDriver driver;
String status;
Logger logger = Logger.getLogger("devpinoyLogger");

public UIOperation(WebDriver driver){
this.driver = driver;
}

public String perform(Properties p,String operation,String objectType,String objectName,String value){
status = "Pass";
switch(operation.toUpperCase()){
case "GOTOURL":
logger.info("Opening Flight Reservation Application.");
driver.get(p.getProperty(objectName));
logger.info("Opened Flight Reservation Application Successfully.");
break;
case "SET":
logger.info("Entering '"+value+"' in the '"+objectName+"' field.");
WebElement elementTobeSet = driver.findElement(this.getObject(p,objectType,objectName));
highlightElement(elementTobeSet);
elementTobeSet.clear();
elementTobeSet.sendKeys(value);
logger.info("Entered '"+value+"' in the '"+objectName+"' field.");
break;
case "CLICK":
logger.info("Clicking on '"+objectName+"'.");
WebElement elementTobeClicked = driver.findElement(this.getObject(p,objectType,objectName));
highlightElement(elementTobeClicked);
elementTobeClicked.click();
logger.info("Clicked on '"+objectName+"'.");
break;
case "SELECT":
logger.info("Selecting '"+value+"' from '"+objectName+"' dropdown.");
WebElement elementTobeSelected = driver.findElement(this.getObject(p,objectType,objectName));
highlightElement(elementTobeSelected);
Select select = new Select(elementTobeSelected);
select.selectByVisibleText(value);
logger.info("Selected '"+value+"' from '"+objectName+"' dropdown.");
break;
case "VERIFYTEXT":
logger.info("Verifying Text : "+value);
if(driver.getPageSource().contains(value)){
status = "Pass";
}else{
status = "Fail";
}
logger.info("Verified Text : "+value);
break;
case "VERIFYTITLE":
logger.info("Verifying Title : "+value);
if(driver.getTitle().equals(value)){
status = "Pass";
}else{
status = "Fail";
logger.error("VERIFYTITLE got failed | ##Expected -- "+value+" | ##Actual -- "+driver.getTitle());
}
logger.info("Verified Title : "+value);
break;
case "CLOSEAPP":
logger.info("Closing driver....");
driver.quit();
logger.info("Closed driver...");
}

return status;
}

private void highlightElement(WebElement element){
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].setAttribute('style','background: yellow; border: 2px solid red;');", element);
}

private By getObject(Properties p, String objectType, String objectName){
if(objectType.equals("ID")){
return By.id(p.getProperty(objectName));
}else if(objectType.equals("XPATH")){
return By.xpath(p.getProperty(objectName));
}else if(objectType.equals("NAME")){
return By.name(p.getProperty(objectName));
}else if(objectType.equals("CSS")){
return By.cssSelector(p.getProperty(objectName));
}else if(objectType.equals("LINKTEXT")){
return By.linkText(p.getProperty(objectName));
}else{
status = "Fail";
return null;

}
}

}

ReportGenerator.java (Class File to generate Test Execution Report)
=================================================

package utility; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class ReportGenerator { public static void generatereport(String content) throws IOException{ FileWriter writer = new FileWriter(Constant.reportPath,true); PrintWriter write = new PrintWriter(writer); write.println(content); write.close(); } }


Constant.java (Class File to keep all the final variables)
========================================

package utility;

public class Constant {

public static final String filePath = System.getProperty("user.dir")+"\\TestData";
public static final String fileName = "TestData.xlsx";
public static final String ieDriverPath = System.getProperty("user.dir")+"\\drivers\\IEDriverServer.exe";
public static final String chromeDriverPath = System.getProperty("user.dir")+"\\drivers\\chromedriver.exe";
public static final String reportPath = System.getProperty("user.dir")+"\\Result\\TestExecutionReport.txt";

}

ExecuteTest.java (Class File or Driver Script to control the test case execution)
=========================================================
package testcases;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import excelInputAndOutput.ExcelReader;
import operation.ReadObject;
import operation.UIOperation;
import utility.Constant;
import utility.ReportGenerator;

public class ExecuteTest {
public WebDriver driver;
public String status;
Properties allObjects;
ExcelReader reader = new ExcelReader();
UIOperation operation;
ReadObject object = new ReadObject();


@SuppressWarnings("deprecation")
@BeforeTest
public void testRunner() throws IOException{

allObjects = object.getObjectRepository();
if(allObjects.getProperty("browserType").equals("chrome")){
System.setProperty("webdriver.chrome.driver",Constant.chromeDriverPath);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("useAutomationExtension", false);
driver = new ChromeDriver(options);
}else if(allObjects.getProperty("browserType").equals("ie")){
System.setProperty("webdriver.ie.driver",Constant.ieDriverPath);
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
capabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
capabilities.setCapability(InternetExplorerDriver.INITIAL_BROWSER_URL, allObjects.getProperty("URL"));
driver = new InternetExplorerDriver(capabilities);
}

driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);



File file = new File(Constant.reportPath);
if(file.exists()){
file.delete();
}

ReportGenerator.generatereport("***********************************************************");
ReportGenerator.generatereport("Project Name: Flight Reservation");
ReportGenerator.generatereport("Browser : "+allObjects.getProperty("browserType"));
ReportGenerator.generatereport("Operating System : "+System.getProperty("os.name"));
InetAddress myHost = InetAddress.getLocalHost();
ReportGenerator.generatereport("Machine Name : "+myHost.getHostName());
ReportGenerator.generatereport("Java Version : "+System.getProperty("java.version"));
ReportGenerator.generatereport("User Name : "+System.getProperty("user.name"));
ReportGenerator.generatereport("***********************************************************");
}

@Test public void executeTest() throws IOException{ operation = new UIOperation(driver); Sheet sheet = reader.readExcel(Constant.filePath, Constant.fileName); int rowNum = sheet.getLastRowNum()-sheet.getFirstRowNum(); for(int i=1;i<=rowNum;i++){ Row row = sheet.getRow(i); if(row.getCell(0).getStringCellValue().length() == 0){ status = operation.perform(allObjects, row.getCell(1).getStringCellValue().trim(), row.getCell(2).getStringCellValue().trim(), row.getCell(3).getStringCellValue().trim(), row.getCell(4).getStringCellValue().trim()); ReportGenerator.generatereport(row.getCell(1).getStringCellValue().trim()+"---"+row.getCell(2).getStringCellValue().trim()+"---"+row.getCell(3).getStringCellValue().trim()+"---"+row.getCell(4).getStringCellValue().trim()+"---"+status); Cell cell = row.getCell(5); cell.setCellValue(status); cell.setCellStyle(reader.customizeCell(status)); }else{ ReportGenerator.generatereport("================================================================"); ReportGenerator.generatereport("New TestCase : "+row.getCell(0).getStringCellValue().trim()); ReportGenerator.generatereport("================================================================"); } } reader.generateReport(new File(Constant.filePath+"\\"+Constant.fileName)); reader.closeExcel(); }


@AfterTest
public void tearDown(){
driver.quit();

}
}

testng.xml
========

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
  <test thread-count="5" name="Test">
    <classes>
      <class name="testcases.ExecuteTest"/>
    </classes>
  </test> <!-- Test -->
</suite> <!-- Suite -->

testRunner.bat (A batch file to initiate execution)
====================================

H:
Set projectLocation=H:\Workspace_Selenium\FlightReservation(Keyword)
cd %projectLocation%
Set classPath=%projectLocation%/bin;%projectLocation%/libs/*
java org.testng.TestNG testng.xml
pause


TestData.xlsx
==========


Test Execution Report  (Text File) 
==========================

***********************************************************
Project Name: Flight Reservation
Browser : chrome
Operating System : Windows 7
Machine Name : NTS-PC
Java Version : 1.8.0_162
User Name : MahapaRa
***********************************************************
================================================================
New TestCase : Launch Flight Reservation Application
================================================================
GOTOURL------URL------Pass
VERIFYTITLE---------Welcome: Mercury Tours---Pass
================================================================
New TestCase : Login To Flight Reservation Application
================================================================
SET---NAME---userID---mercury---Pass
SET---NAME---password---mercury---Pass
CLICK---NAME---Sign-In------Pass
VERIFYTITLE---------Find a Flight: Mercury Tours:---Pass
================================================================
New TestCase : Book A Ticket
================================================================
CLICK---XPATH---oneWayTrip------Pass
SELECT---NAME---departureFrom---London---Pass
SELECT---NAME---arrivalTo---Paris---Pass
CLICK---XPATH---classPreference------Pass
SELECT---NAME---airlinePreference---Blue Skies Airlines---Pass
CLICK---NAME---findFlights------Pass
CLICK---NAME---reserveFlights------Pass
SET---NAME---firstName---Rajendra---Pass
SET---NAME---lastName---Mahapatra---Pass
SET---NAME---creditCardNumber---957689765---Pass
CLICK---NAME---buyFlights------Pass
VERIFYTITLE---------Flight Confirmation: Mercury Tours---Pass
CLOSEAPP------------Pass



Test Execution Report   (Excel File)
===========================



Log File (Manual.logs)  
=================

24/04/2018 15:41:35 devpinoyLogger Opening Flight Reservation Application.
24/04/2018 15:41:39 devpinoyLogger Opened Flight Reservation Application Successfully.
24/04/2018 15:41:39 devpinoyLogger Verifying Title : Welcome: Mercury Tours
24/04/2018 15:41:39 devpinoyLogger Verified Title : Welcome: Mercury Tours
24/04/2018 15:41:39 devpinoyLogger Entering 'mercury' in the 'userID' field.
24/04/2018 15:41:39 devpinoyLogger Entered 'mercury' in the 'userID' field.
24/04/2018 15:41:39 devpinoyLogger Entering 'mercury' in the 'password' field.
24/04/2018 15:41:39 devpinoyLogger Entered 'mercury' in the 'password' field.
24/04/2018 15:41:39 devpinoyLogger Clicking on 'Sign-In'.
24/04/2018 15:42:37 devpinoyLogger Clicked on 'Sign-In'.
24/04/2018 15:42:37 devpinoyLogger Verifying Title : Find a Flight: Mercury Tours:
24/04/2018 15:42:37 devpinoyLogger Verified Title : Find a Flight: Mercury Tours:
24/04/2018 15:42:37 devpinoyLogger Clicking on 'oneWayTrip'.
24/04/2018 15:42:37 devpinoyLogger Clicked on 'oneWayTrip'.
24/04/2018 15:42:37 devpinoyLogger Selecting 'London' from 'departureFrom' dropdown.
24/04/2018 15:42:38 devpinoyLogger Selected 'London' from 'departureFrom' dropdown.
24/04/2018 15:42:38 devpinoyLogger Selecting 'Paris' from 'arrivalTo' dropdown.
24/04/2018 15:42:38 devpinoyLogger Selected 'Paris' from 'arrivalTo' dropdown.
24/04/2018 15:42:38 devpinoyLogger Clicking on 'classPreference'.
24/04/2018 15:42:38 devpinoyLogger Clicked on 'classPreference'.
24/04/2018 15:42:38 devpinoyLogger Selecting 'Blue Skies Airlines' from 'airlinePreference' dropdown.
24/04/2018 15:42:38 devpinoyLogger Selected 'Blue Skies Airlines' from 'airlinePreference' dropdown.
24/04/2018 15:42:38 devpinoyLogger Clicking on 'findFlights'.
24/04/2018 15:42:39 devpinoyLogger Clicked on 'findFlights'.
24/04/2018 15:42:39 devpinoyLogger Clicking on 'reserveFlights'.
24/04/2018 15:42:40 devpinoyLogger Clicked on 'reserveFlights'.
24/04/2018 15:42:40 devpinoyLogger Entering 'Rajendra' in the 'firstName' field.
24/04/2018 15:42:41 devpinoyLogger Entered 'Rajendra' in the 'firstName' field.
24/04/2018 15:42:41 devpinoyLogger Entering 'Mahapatra' in the 'lastName' field.
24/04/2018 15:42:41 devpinoyLogger Entered 'Mahapatra' in the 'lastName' field.
24/04/2018 15:42:41 devpinoyLogger Entering '957689765' in the 'creditCardNumber' field.
24/04/2018 15:42:41 devpinoyLogger Entered '957689765' in the 'creditCardNumber' field.
24/04/2018 15:42:42 devpinoyLogger Clicking on 'buyFlights'.
24/04/2018 15:42:42 devpinoyLogger Clicked on 'buyFlights'.
24/04/2018 15:42:42 devpinoyLogger Verifying Title : Flight Confirmation: Mercury Tours
24/04/2018 15:42:42 devpinoyLogger Verified Title : Flight Confirmation: Mercury Tours
24/04/2018 15:42:42 devpinoyLogger Closing driver....
24/04/2018 15:42:44 devpinoyLogger Closed driver...

Comments

Popular posts from this blog

Encoding and Decoding in Selenium using Base64 Class of Java

Parallel Execution In TestNG Framework Using ThreadLocal Concept

How to handle calendar or date picker using dynamic XPATH?