Hybrid Framework in Selenium with Extent Reporting....
Package Structure :
ExcelReader.java
--------------------------
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;
}
}
ReadObject.java
----------------------
package operation;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class ReadObject {
public Properties getObjectRepository() throws IOException{
Properties p = new Properties();
File file = new File(System.getProperty("user.dir")+"\\src\\objects.properties");
FileInputStream stream = new FileInputStream(file);
p.load(stream);
return p;
}
}
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";
}
ExcelReader.java
--------------------------
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;
}
}
ReadObject.java
----------------------
package operation;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class ReadObject {
public Properties getObjectRepository() throws IOException{
Properties p = new Properties();
File file = new File(System.getProperty("user.dir")+"\\src\\objects.properties");
FileInputStream stream = new FileInputStream(file);
p.load(stream);
return p;
}
}
UIOperation.java
------------------------
package operation;
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;
import org.testng.Assert;
import testcases.ExecuteTest;
public class UIOperation extends ExecuteTest {
static Logger logger = Logger.getLogger("FlightReservation");
/* Function Name : launchURL
* Parameters : URL(String)
* Description: This function invokes the application URL. */
public static void launchURL(WebDriver driver,String URL){
logger.info("Opening Flight Reservation Application.");
System.out.println(driver);
driver.get(URL);
logger.info("Opened Flight Reservation Application Successfully.");
}
/* Function Name : sendKeys
* Parameters : locator(By),objectName(String),value(String)
* Description: This function enters the specified value in the edit field. */
public static void sendKeys(By locator,String objectName,String value){
logger.info("Entering '"+value+"' in the '"+objectName+"' field.");
WebElement elementTobeSet = driver.findElement(locator);
highlightElement(elementTobeSet);
elementTobeSet.clear();
elementTobeSet.sendKeys(value);
logger.info("Entered '"+value+"' in the '"+objectName+"' field.");
}
/* Function Name : click
* Parameters : locator(By),objectName(String)
* Description: This function clicks the web object. */
public static void click(By locator,String objectName){
logger.info("Clicking on '"+objectName+"'.");
WebElement elementTobeClicked = driver.findElement(locator);
highlightElement(elementTobeClicked);
elementTobeClicked.click();
logger.info("Clicked on '"+objectName+"'.");
}
/* Function Name : select
* Parameters : locator(By),objectName(String),value(String)
* Description: This function selects the specified value from the web list. */
public static void select(By locator,String objectName,String value){
logger.info("Selecting '"+value+"' from '"+objectName+"' dropdown.");
WebElement elementTobeSelected = driver.findElement(locator);
highlightElement(elementTobeSelected);
Select select = new Select(elementTobeSelected);
select.selectByVisibleText(value);
logger.info("Selected '"+value+"' from '"+objectName+"' dropdown.");
}
/* Function Name : verifyTextOnWebPage
* Parameters : value(String)
* Description: This function verifies the presence of specified text on the web page. */
public static void verifyTextOnWebPage(String value){
logger.info("Verifying Text : "+value);
Assert.assertTrue(driver.getPageSource().contains(value));
logger.info("Verified Text : "+value);
}
/* Function Name : verifyTitle
* Parameters : value(String)
* Description: This function verifies the page title. */
public static void verifyTitle(String value){
logger.info("Verifying Title : "+value);
Assert.assertEquals(driver.getTitle(), value);
logger.info("Verified Title : "+value);
}
/* Function Name : closeApp
* Parameters : Nil
* Description: This function quits the driver */
public static void closeApp(){
logger.info("Closing driver....");
driver.quit();
logger.info("Closed driver...");
}
private static void highlightElement(WebElement element){
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].setAttribute('style','background: yellow; border: 2px solid red;');", element);
}
}
Constant.java
------------------
Constant.java
------------------
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
----------------------
package testcases;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
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.openqa.selenium.remote.RemoteWebDriver;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
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 excelInputAndOutput.ExcelReader;
import operation.ReadObject;
import operation.UIOperation;
import utility.Constant;
public class ExecuteTest {
public static WebDriver driver;
ExcelReader reader = new ExcelReader();
ReadObject object = new ReadObject();
Properties allObjects = null;
ExtentReports extent;
ExtentTest logger;
ExtentHtmlReporter htmlreporter;
@SuppressWarnings("deprecation")
@BeforeTest
public void setUP() throws IOException{
allObjects = object.getObjectRepository();
extent = new ExtentReports();
htmlreporter = new ExtentHtmlReporter(new File(Constant.reportPath));
htmlreporter.config().setChartVisibilityOnOpen(true);
htmlreporter.config().setDocumentTitle("Test Execution Report : Flight Reservation");
htmlreporter.config().setReportName("Regression Cycle");
htmlreporter.config().setTestViewChartLocation(ChartLocation.BOTTOM);
htmlreporter.config().setTheme(Theme.DARK);
extent.attachReporter(htmlreporter);
extent.setSystemInfo("Project Name", "Flight Reservation");
extent.setSystemInfo("Environemnt", "Production");
extent.setSystemInfo("OS", System.getProperty("os.name"));
extent.setSystemInfo("username", System.getProperty("user.name"));
InetAddress myHost = InetAddress.getLocalHost();
extent.setSystemInfo("Host",myHost.getHostName());
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);
//driver = new RemoteWebDriver(new URL("http://http://10.28.110.82/wd/hub"),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);
System.out.println(driver);
}
@Test(priority=0)
public void LaunchFlightReservationApplication() throws IOException{
logger = extent.createTest("LaunchFlightReservationApplication");
String URL = reader.getCellData(Constant.filePath, Constant.fileName, "InvokeApplication", 1, 0);
String expTitle = reader.getCellData(Constant.filePath, Constant.fileName, "InvokeApplication", 1, 1);
UIOperation.launchURL(driver,URL);
UIOperation.verifyTitle(expTitle);
//logger.log(Status.PASS, "Flight Reservation Application has been launces 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);
// Enter UserName
UIOperation.sendKeys(By.name(allObjects.getProperty("userID")), "userName", userName);
// Enter Password
UIOperation.sendKeys(By.name(allObjects.getProperty("password")), "password", password);
// Click on 'Sign-In' button
UIOperation.click(By.name(allObjects.getProperty("Sign-In")),"Sign-In");
// Verify page Title
UIOperation.verifyTitle(expTitle);
//logger.log(Status.PASS, "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);
// Select Trip Type
UIOperation.click(By.xpath(allObjects.getProperty("oneWayTrip")), "One Way");
// Select Fly From
UIOperation.select(By.name(allObjects.getProperty("departureFrom")), "Fly From", flyFrom);
// Select Fly To
UIOperation.select(By.name(allObjects.getProperty("arrivalTo")), "Fly To", flyTo);
// Select Class Preference
UIOperation.click(By.xpath(allObjects.getProperty("classPreference")), "First");
// Select Airline Preference
UIOperation.select(By.name(allObjects.getProperty("airlinePreference")), "Airline Preference",airlinePreference);
// Click on 'Find Flights' button
UIOperation.click(By.name(allObjects.getProperty("findFlights")), "Find Flights");
// Click on 'Reserve Flights' button
UIOperation.click(By.name(allObjects.getProperty("reserveFlights")),"Reserve Flights");
// Enter First Name
UIOperation.sendKeys(By.name(allObjects.getProperty("firstName")), "First Name", firstName);
// Enter Last Name
UIOperation.sendKeys(By.name(allObjects.getProperty("lastName")), "Last Name", lastName);
// Enter Credit Number
UIOperation.sendKeys(By.name(allObjects.getProperty("creditCardNumber")), "Credit Number", creditNumber);
// Click on 'Buy Flights' button
UIOperation.click(By.name(allObjects.getProperty("buyFlights")), "Buy Flights");
// Verify Ticket booking is successful
UIOperation.verifyTextOnWebPage(expText);
//logger.log(Status.PASS, "Ticket has been 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));
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.GREEN));
String screenShotPath = getScreenshot(result.getName());
logger.addScreenCaptureFromPath(screenShotPath);
}
}
@AfterTest
public void tearDown(){
UIOperation.closeApp();
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;
}
}
objects.properties
--------------------------
browserType=chrome
URL=http://newtours.demoaut.com
userID=userName
password=password
Sign-In=login
oneWayTrip=//input[@name='tripType'][@value='oneway']
departureFrom=fromPort
arrivalTo=toPort
classPreference=//input[@name='servClass'][@value='First']
airlinePreference=airline
findFlights=findFlights
reserveFlights=reserveFlights
firstName=passFirst0
lastName=passLast0
creditCardNumber=creditnumber
buyFlights=buyFlights
Log4j.properties
--------------------------
#Root logger
log4j.rootLogger=DEBUG,file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=H:\\Workspace_Selenium\\FlightReservation(Hybrid)\\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(Hybrid)\\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">
<classes>
<class name="testcases.ExecuteTest"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
testngRunner.bat
----------------------
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
-------------------
Comments
Post a Comment