Page Object Model Framework In Selenium with Extent Reporting...

Package Structure:



































ExcelReader.java (A Class file to fetch data from Excel)
==========================================
package excelInputAndOutput;

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

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelReader {

Workbook workbook;
public String getCellData(String filePath,String fileName, String sheetName, int rowno, int colno) throws IOException{
File file = new File(filePath+"\\"+fileName);
FileInputStream 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(sheetName);
Row row = sheet.getRow(rowno);
String data = row.getCell(colno).getStringCellValue();
workbook.close();
return data;

}

}

LoginToFR.java (A Page Factory Class to contain all the web elements and functions related to 'Login' Page)
========================================================================

package pagefactory;

import org.apache.log4j.Logger;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class LoginToFR {
WebDriver driver;
private Logger logger = Logger.getLogger("flightReservation");

@FindBy(name="userName")
WebElement username;
@FindBy(name="password")
WebElement password;
@FindBy(name="login")
    WebElement signOn;

public LoginToFR(WebDriver driver){
this.driver = driver;
PageFactory.initElements(driver, this);

}
// Enter User Name
private void setUserName(String un){
highlightElement(username);
username.clear();
logger.info("Entering '"+un+"' in the 'UserName' edit field...");
username.sendKeys(un);
logger.info("Entered '"+un+"' in the 'UserName' edit field...");
}

// Enter Password
private void setPassword(String pwd){
highlightElement(password);
password.clear();
logger.info("Entering '"+pwd+"' in the 'Password' edit field...");
password.sendKeys(pwd);
logger.info("Entered '"+pwd+"' in the 'Password' edit field...");

}

// Click on 'Sign-On'
private void clickOnSignOn(){
highlightElement(signOn);
logger.info("Clicking on 'Sign On' button...");
signOn.click();
logger.info("Clicked on 'Sign On' button...");
}

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

public void loginToFlightReservation(String un, String pwd){
setUserName(un);
setPassword(pwd);
clickOnSignOn();

}
}


FindAFlight.java (A Page Factory Class file to contain all the web elements and functions related to 'Find A Flight' Page)
=======================================================================

package pagefactory;

import org.apache.log4j.Logger;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

public class FindAFlight {
WebDriver driver;
private Logger logger = Logger.getLogger("flightReservation");
@FindBy(xpath="//input[@name='tripType'][@value='oneway']")
WebElement oneway;
@FindBy(name="fromPort")
WebElement departureFrom;
@FindBy(name="toPort")
WebElement arrivalTo;
@FindBy(xpath="//input[@name='servClass'][@value='First']")
WebElement firstClass;
@FindBy(name="airline")
WebElement airlinePreference;
@FindBy(name="findFlights")
WebElement findFlights;
public FindAFlight(WebDriver driver){
this.driver = driver;
PageFactory.initElements(driver, this);
}
// Select 'one way' trip
private void selectOneWayTrip(){
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.visibilityOf(oneway));
highlightElement(oneway);
logger.info("Clicking on 'oneway' trip type...");
oneway.click();
logger.info("Clicked on 'oneway' trip type...");
}
// Select 'Departure From'
private void selectDepartureFrom(String flyFrom){
highlightElement(departureFrom);
logger.info("Selecting '"+flyFrom+"' from 'Departure From' dropdown...");
Select select = new Select(departureFrom);
select.selectByVisibleText(flyFrom);
logger.info("Selected '"+flyFrom+"' from 'Departure From' dropdown...");
}
// Select 'Arrival To'
private void selectArrivalTo(String flyTo){
highlightElement(arrivalTo);
logger.info("Selecting '"+flyTo+"' from 'Arrival To' dropdown...");
Select select = new Select(arrivalTo);
select.selectByVisibleText(flyTo);
logger.info("Selected '"+flyTo+"' from 'Arrival To' dropdown...");
}
// Select Class Preference
private void selectclassPreference(){
highlightElement(firstClass);
logger.info("Clicking on 'First' class preference...");
firstClass.click();
logger.info("Clicked on 'First' class preference...");
}
// Select Airline Preference
private void selectAirlinePreference(String preferredAirline){
highlightElement(airlinePreference);
logger.info("Selecting '"+preferredAirline+"' from 'Airline Preference' dropdown...");
Select select = new Select(airlinePreference);
select.selectByVisibleText(preferredAirline);
logger.info("Selected '"+preferredAirline+"' from 'Airline Preference' dropdown...");
}
// Click on 'Find Flights'
private void clickOnFindFlights(){
highlightElement(findFlights);
logger.info("Clicking on 'Find Flights' button...");
findFlights.click();
logger.info("Clicked on 'Find Flights' button...");
}
private void highlightElement(WebElement element){
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].setAttribute('style','background: yellow; border: 2px solid red;');", element);
}
public void findAFlightByEnteringFlightDetails(String flyFrom, String flyTo, String preferredAirline){
selectOneWayTrip();
selectDepartureFrom(flyFrom);
selectArrivalTo(flyTo);
selectclassPreference();
selectAirlinePreference(preferredAirline);
clickOnFindFlights();
}
}


BookAFlight.java (A Page Factory Class file to contains all the web elements and functions related to 'Book A Flight' page)
======================================================================
package pagefactory;

import org.apache.log4j.Logger;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class BookAFlight {
WebDriver driver;
private Logger logger = Logger.getLogger("flightReservation");

@FindBy(name="passFirst0")
WebElement firstName;
@FindBy(name="passLast0")
WebElement lastName;
@FindBy(name="creditnumber")
WebElement ccNumber;
@FindBy(name="buyFlights")
WebElement buyFlights;

public BookAFlight(WebDriver driver){
this.driver=driver;
PageFactory.initElements(driver, this);
}

// Enter First Name
private void setFirstName(String firstname){
highlightElement(firstName);
firstName.clear();
logger.info("Entering '"+firstname+"' in the 'First Name' edit field...");
firstName.sendKeys(firstname);
logger.info("Entered '"+firstname+"' in the 'First Name' edit field...");
}
// Enter Last Name
private void setLastName(String lastname){
highlightElement(lastName);
lastName.clear();
logger.info("Entering '"+lastname+"' in the 'Last Name' edit field...");
lastName.sendKeys(lastname);
logger.info("Entered '"+lastname+"' in the 'Last Name' edit field...");
}

// Enter Credit Card Number
private void setCreditCardNumber(String ccnumber){
highlightElement(ccNumber);
ccNumber.clear();
logger.info("Entering '"+ccnumber+"' in the 'Credit Number' edit field...");
ccNumber.sendKeys(ccnumber);
logger.info("Entered '"+ccnumber+"' in the 'Credit Number' edit field...");
}

// Click on 'Buy Flights' 
private void clickOnBuyFlights(){
highlightElement(buyFlights);
logger.info("Clicking on 'Buy Flights' button...");
buyFlights.click();
logger.info("Clicked on 'Buy Flights' button...");
}


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


public void bookAFlightByEnteringPersonalDetails(String firstname,String lastname,String ccnumber){
setFirstName(firstname);
setLastName(lastname);
setCreditCardNumber(ccnumber);
clickOnBuyFlights();
}

}


ReserveAFlight.java (A Page Factory Class file to contain all the web elements and functions related to 'Reserve A Flight' page)
======================================================================

package pagefactory;

import org.apache.log4j.Logger;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class ReserveAFlight {
WebDriver driver;
private Logger logger = Logger.getLogger("flightReservation");
@FindBy(name="reserveFlights")
WebElement reserveFlights;
public ReserveAFlight(WebDriver driver){
this.driver=driver;
PageFactory.initElements(driver, this);
}
public void clickOnReserveFlights(){
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.visibilityOf(reserveFlights));
highlightElement(reserveFlights);
logger.info("Clicking on 'Reserve Flights' button...");
reserveFlights.click();
logger.info("Clicked on 'Reserve Flights' button...");
}
private void highlightElement(WebElement element){
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].setAttribute('style','background: yellow; border: 2px solid red;');", element);
}

}


FlightConfirmation.java (A Page Factory Class file to contain all the web elements and functions related to 'Flight Confirmation' page
====================================================================

package pagefactory;

import org.apache.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.Assert;

public class FlightConfirmation {
WebDriver driver;
private Logger logger = Logger.getLogger("flightReservation");
public FlightConfirmation(WebDriver driver){
this.driver=driver;
PageFactory.initElements(driver, this);
}
public void assertFlightBookingConfirmationText(String expText){
logger.info("Verifying '"+expText+"' on web page...");
Assert.assertTrue(driver.getPageSource().contains(expText));
logger.info("Verifyied '"+expText+"' on web page...");
}
}


Constant.java ( A Class file to contain all the constant 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.html";

}


ExecuteTest.java (Driver Script to execute the test cases using TestNg)
===================================================

package testcases;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
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.Assert;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.MarkupHelper;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.ChartLocation;
import com.aventstack.extentreports.reporter.configuration.Theme;

//import com.relevantcodes.extentreports.ExtentReports;
//import com.relevantcodes.extentreports.ExtentTest;
//import com.relevantcodes.extentreports.LogStatus;

import excelInputAndOutput.ExcelReader;
import pagefactory.BookAFlight;
import pagefactory.FindAFlight;
import pagefactory.FlightConfirmation;
import pagefactory.LoginToFR;
import pagefactory.ReserveAFlight;
import utility.Constant;


public class ExecuteTest {
public static WebDriver driver;
ExcelReader reader = new ExcelReader();
String URL = null;
BookAFlight bookaflight;
LoginToFR logintofr;
ReserveAFlight reserveaflight;
FindAFlight findaflight;
FlightConfirmation flightconfirmation;
ExtentHtmlReporter htmlReporter;
ExtentReports extent;
ExtentTest logger;
@SuppressWarnings("deprecation")
@BeforeTest
@Parameters({"browserType"})
public void setUP(String browserType) throws IOException{
extent = new ExtentReports();
htmlReporter = new ExtentHtmlReporter(new File(Constant.reportPath));
//htmlReporter.setAppendExisting(true);
//Locale.setDefault(Locale.ENGLISH);
htmlReporter.config().setChartVisibilityOnOpen(true);
htmlReporter.config().setDocumentTitle("Flight Reservation : Test Execution Report");
htmlReporter.config().setReportName("Regression Cycle");
htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);
htmlReporter.config().setTheme(Theme.DARK);
extent.attachReporter(htmlReporter);
extent.setSystemInfo("Project", "FlightReservation");
extent.setSystemInfo("Environment", "Production");
extent.setSystemInfo("OS", System.getProperty("os.name"));
InetAddress myHost = InetAddress.getLocalHost();
extent.setSystemInfo("Host Name", myHost.getHostName());
extent.setSystemInfo("User", System.getProperty("user.name"));
if(browserType.equals("chrome")){
System.setProperty("webdriver.chrome.driver",Constant.chromeDriverPath);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("useAutomationExtension", false);
driver = new ChromeDriver(options);
}else if(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);
URL = reader.getCellData(Constant.filePath, Constant.fileName, "InvokeApplication", 1, 0);
capabilities.setCapability(InternetExplorerDriver.INITIAL_BROWSER_URL, URL);
driver = new InternetExplorerDriver(capabilities);
}
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
System.out.println(driver);
}
@Test(priority=0)
public void launchFlightReservationApplication() throws IOException{
logger = extent.createTest("launchFlightReservationApplication");
URL = reader.getCellData(Constant.filePath, Constant.fileName, "InvokeApplication", 1, 0);
String expTitle = reader.getCellData(Constant.filePath, Constant.fileName, "InvokeApplication", 1, 1);
driver.get(URL);
// Verify page Title
Assert.assertEquals(driver.getTitle(), expTitle);
//logger.log(Status.PASS, "Flight Reservation Application got invoked successfully...");
}
@Test(priority=1)
public void loginToFlightReservation() throws IOException {
logger = extent.createTest("loginToFlightReservation");
String userName = reader.getCellData(Constant.filePath, Constant.fileName, "Login", 1, 0);
String password = reader.getCellData(Constant.filePath, Constant.fileName, "Login", 1, 1);
String expTitle = reader.getCellData(Constant.filePath, Constant.fileName, "Login", 1, 2);
// Login To Flight Reservation
logintofr = new LoginToFR(driver);
logintofr.loginToFlightReservation(userName, password);
// Verify page Title
Assert.assertEquals(driver.getTitle(), expTitle);
//logger.log(Status.PASS, "Flight Reservation Login Successful...");
}
@Test(priority=2)
public void bookATicket() throws IOException{
logger = extent.createTest("bookATicket");
String flyFrom = reader.getCellData(Constant.filePath, Constant.fileName, "BookATicket", 1, 0);
String flyTo = reader.getCellData(Constant.filePath, Constant.fileName, "BookATicket", 1, 1);
String airlinePreference = reader.getCellData(Constant.filePath, Constant.fileName, "BookATicket", 1, 2);
String firstName = reader.getCellData(Constant.filePath, Constant.fileName, "BookATicket", 1, 3);
String lastName = reader.getCellData(Constant.filePath, Constant.fileName, "BookATicket", 1, 4);
String creditNumber = reader.getCellData(Constant.filePath, Constant.fileName, "BookATicket", 1, 5);
String expText = reader.getCellData(Constant.filePath, Constant.fileName, "BookATicket", 1, 6);
findaflight = new FindAFlight(driver);
findaflight.findAFlightByEnteringFlightDetails(flyFrom, flyTo, airlinePreference);
reserveaflight = new ReserveAFlight(driver);
reserveaflight.clickOnReserveFlights();
bookaflight = new BookAFlight(driver);
bookaflight.bookAFlightByEnteringPersonalDetails(firstName, lastName, creditNumber);
flightconfirmation = new FlightConfirmation(driver);
flightconfirmation.assertFlightBookingConfirmationText(expText);
//logger.log(Status.PASS, "Ticket got booked successfully");
}
@AfterMethod
public void generateReport(ITestResult result) throws IOException{
if(result.getStatus() == ITestResult.FAILURE){
logger.log(Status.FAIL, MarkupHelper.createLabel(result.getName()+" :  got failed due to "+result.getThrowable(), ExtentColor.RED));
logger.log(Status.FAIL, result.getName()+" :  got failed due to "+result.getThrowable());
String screenshotPath = getScreenshot(result.getName());
logger.addScreenCaptureFromPath(screenshotPath);
}else if(result.getStatus() == ITestResult.SKIP){
logger.log(Status.SKIP, MarkupHelper.createLabel(result.getName()+" got skipped as it was not ready to be executed...",ExtentColor.YELLOW));
}else if(result.getStatus() == ITestResult.SUCCESS){
logger.log(Status.PASS, MarkupHelper.createLabel(result.getName()+" : got passed", ExtentColor.CYAN));
String screenshotPath = getScreenshot(result.getName());
logger.addScreenCaptureFromPath(screenshotPath);
}
}
@AfterTest
public void tearDown(){
driver.quit();
extent.flush();
}
private String getScreenshot(String screenshotName) throws IOException{
TakesScreenshot srcShot = (TakesScreenshot)driver;
File srcFile = srcShot.getScreenshotAs(OutputType.FILE);
String dateName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
String destination = System.getProperty("user.dir")+"\\screenshots\\"+screenshotName+"_"+dateName+".png";
File destFile = new File(destination);
FileUtils.copyFile(srcFile, destFile);
return destination;
}
}


Log4j.properties
=============
#Root logger

log4j.rootLogger=DEBUG,file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=H:\\Workspace_Selenium\\FlightReservation(POM)\\Result\\Selenium.logs
log4j.appender.file.maxFileSize=900KB
log4j.appender.file.maxBackupIndex=5
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c<strong>{1}</strong>:%L - %m%n
log4j.appender.file.Append=false
#Application Logs

log4j.logger.flightReservation=DEBUG, dest1
log4j.appender.dest1=org.apache.log4j.RollingFileAppender
log4j.appender.dest1.maxFileSize=900KB
log4j.appender.dest1.maxBackupIndex=6
log4j.appender.dest1.layout=org.apache.log4j.PatternLayout
log4j.appender.dest1.layout.ConversionPattern=%d{dd/MM/yyyy HH:mm:ss} %c %m%n
log4j.appender.dest1.File=H:\\Workspace_Selenium\\FlightReservation(POM)\\Result\\FlightReservation.logs
log4j.appender.dest1.Append=false

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">
  <parameter name="browserType" value="chrome" />
    <classes>
      <class name="testcases.ExecuteTest"/>
    </classes>
  </test> <!-- Test -->
</suite> <!-- Suite -->

testRunner.bat ( A batch File to initiate Batch Execution)
============================================
H:
Set projectLocation=H:\Workspace_Selenium\FlightReservation(Hybrid)
cd %projectLocation%
Set classPath=%projectLocation%/bin;%projectLocation%/libs/*
java org.testng.TestNG testng.xml
pause

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

Sheet Name: InvokeApplication





Sheet Name : Login





Sheet Name: BookATicket






Test Execution Report (Extent Report) :
===============================


Comments

  1. Thank you for your compliment... Please keep vising my blogs to see new posts.....

    ReplyDelete
  2. Hello Sir
    Where to use
    @Listeners(ExtentITestListenerClassAdapter.class) listner.

    ReplyDelete
    Replies
    1. You Can use it either class level or suite level.....

      Delete

Post a Comment

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?