Selenium Framework, Data Driven, Keyword and Hybrid Framework Tutorials by Shiva Sir

3

It provides predefined libraries to implement a test script with a design pattern.
The framework uses an external file to take test data which will be implemented into the test script.
We will perform file handling operations using the Apache POI library by Jar integration or Maven.
Type of Selenium Framework:-
1 Data-Driven Framework:-    
we will create an external excel file or CSV file and define all Test data which will be read by File Handling operation and implemented in Test Script.
1.1 Create Environment using APACHE POI, SELENIUM, TestNG
Download apache poi using the following link
https://archive.apache.org/dist/poi/release/bin/
1.2 Create Excel File I have created scs.excel


1.3 Write the following Code
Data Driven Framework Code using Maven Project;-
Java File:-
package com.scs;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFCreationHelper;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.google.common.collect.Table.Cell;
public class CheckTestData {
ChromeDriver driver;
XSSFWorkbook workbook;
XSSFSheet sheet;
XSSFCell cell;
@BeforeTest
  public void TestSetup()
{
    System.setProperty("webdriver.chrome.driver", "c://chromedriver.exe");
   driver = new ChromeDriver();
   driver.get("https://eroomrent.in/ownerlogin.php");
   driver.manage().window().maximize();
      }
  @Test
  public void f() {
  try
  {
   File src=new File("d://testdata.xlsx"); 
   FileInputStream finput = new FileInputStream(src);
  
   workbook = new XSSFWorkbook(finput);
   sheet=  workbook.getSheetAt(0);
   for(int i=1; i<=sheet.getLastRowNum(); i++)
   {
   cell = sheet.getRow(i).getCell(0);
 
//   cell.setCellType(CellType.STRING); 
   driver.findElement(By.name("txtEmail")).sendKeys(cell.getStringCellValue());
  
   cell = sheet.getRow(i).getCell(1);
  // cell.setCellType(XSSFCell.CELL_TYPE_STRING);
   cell.setCellType(CellType.STRING); 
   driver.findElement(By.name("txtPassword")).sendKeys(cell.getStringCellValue());
   cell.setCellType(CellType.STRING); 
   WebElement we = driver.findElement(By.name("btnsubmit"));
   we.click();
   String s1 = "";
   s1 = "pass";
    
   XSSFRow row = sheet.getRow(1);
//  int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum();
//  XSSFRow newRow = sheet.createRow(1);
     XSSFCell cell = row.createCell(2);
        cell.setCellValue(s1);
             finput.close();
FileOutputStream fout = new FileOutputStream(src); 
workbook.write(fout);
fout.close();
   }
  }
  catch(Exception ex)
  {
  System.out.print(ex.getMessage().toString());
  }
  }
}  
 
POM.XML
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.scs</groupId>
  <artifactId>Testproject</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>Testproject</name>
  <url>http://maven.apache.org</url>
<properties>
     <maven.compiler.source>1.8</maven.compiler.source>
     <maven.compiler.target>1.8</maven.compiler.target>
</properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>7.6.1</version>
    <scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>4.4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.2</version>
</dependency>
  </dependencies>
</project>
Complete Code of Data-Driven Framework:-
package datadrivenexample;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class DataDrivenExample {
ChromeDriver driver;
XSSFWorkbook workbook;
XSSFSheet sheet;
XSSFCell cell;
@BeforeTest
  public void TestSetup()
{   
   System.setProperty("webdriver.chrome.driver", "c://chromedriver.exe");
   driver = new ChromeDriver();
   driver.get("https://eroomrent.in/login.php");
   driver.manage().window().maximize();
   }
  @Test
  public void f() {
  try
  {
   File src=new File("d://test.xlsx"); 
   FileInputStream finput = new FileInputStream(src);
   workbook = new XSSFWorkbook(finput);
   sheet= workbook.getSheetAt(0);
   for(int i=1; i<=sheet.getLastRowNum(); i++)
   {
   cell = sheet.getRow(i).getCell(0);
   cell.setCellType(CellType.STRING);
   driver.findElement(By.name("txtEmail")).sendKeys(cell.getStringCellValue());
   cell = sheet.getRow(i).getCell(1);
   cell.setCellType(CellType.STRING);
  driver.findElement(By.name("txtPassword")).sendKeys(cell.getStringCellValue());
   WebElement we = driver.findElement(By.name("btnsubmit"));
   we.click();
   String s = driver.switchTo().alert().getText();
   driver.switchTo().alert().accept();
   System.out.println(s);
   if(s.equals("Invalid userid and password"))
   {
   System.out.println("fail");
   }
   else
   {
   System.out.println("pass");
   }
   finput.close();
   cell = sheet.getRow(i).createCell(2);
   //cell.setCellType(CellType.STRING);
   cell.setCellValue(s);
FileOutputStream fout = new FileOutputStream(src); 
workbook.write(fout);
fout.close();
   }
  }
  catch(Exception ex)
  {
  System.out.print(ex.getMessage().toString());
  }
  }
}
Another example of Data Driven Framework:-
package scs;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Hello {
ChromeDriver driver;
  XSSFWorkbook workbook;
  XSSFSheet sheet;
  XSSFCell cell;
  @BeforeTest
  public void TestSetup()
{   
   System.setProperty("webdriver.chrome.driver", "d://chromedriver.exe");
   driver = new ChromeDriver();
   driver.get("https://eroomrent.in/login.php");
   driver.manage().window().maximize();
   
}
  @Test
  public void f() {
   try
   {
   File src=new File("d://scs.xlsx");
  
   // Load the file.
   FileInputStream finput = new FileInputStream(src);
  
   // Load he workbook.
  workbook = new XSSFWorkbook(finput);
  
      // Load the sheet in which data is stored.
   sheet= workbook.getSheetAt(0);
  
   for(int i=1; i<=sheet.getLastRowNum(); i++)
   {
    // Import data for Email.
    cell = sheet.getRow(i).getCell(0);
    cell.setCellType(CellType.STRING);
    driver.findElement(By.name("txtEmail")).sendKeys(cell.getStringCellValue());
   
    // Import data for the password.
    cell = sheet.getRow(i).getCell(1);
    cell.setCellType(CellType.STRING);
    driver.findElement(By.name("txtPassword")).sendKeys(cell.getStringCellValue());
    WebElement we = driver.findElement(By.name("btnsubmit"));
    we.click();
         }
   }
   catch(IOException ex)
   {    
   }
  }
}
Another Example of eroomrent.in owner login:-
package scs;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class DatadrivenExample {
ChromeDriver driver;
XSSFWorkbook workbook;
XSSFSheet sheet;
XSSFCell cell;
//HSSFWorkbook workbook;
   // HSSFSheet sheet;
   // HSSFCell cell;
@BeforeTest
  public void TestSetup()
{
      System.setProperty("webdriver.chrome.driver", "c://chromedriver.exe");
   driver = new ChromeDriver();
   driver.get("https://eroomrent.in/ownerlogin.php");
   driver.manage().window().maximize();
   
}
@Test
public void f() {
  try
  {
   File src=new File("d://Testdata1.xlsx"); 
   FileInputStream finput = new FileInputStream(src);
//  workbook = new HSSFWorkbook(finput);
  workbook = new XSSFWorkbook(finput);
   sheet= workbook.getSheetAt(0);
   for(int i=1; i<=sheet.getLastRowNum(); i++)
   {
   cell = sheet.getRow(i).getCell(0);
   cell.setCellType(CellType.STRING);
   driver.findElement(By.name("txtEmail")).sendKeys(cell.getStringCellValue());
   cell = sheet.getRow(i).getCell(1);
   cell.setCellType(CellType.STRING);
   driver.findElement(By.name("txtPassword")).sendKeys(cell.getStringCellValue());
   WebElement we = driver.findElement(By.name("btnsubmit"));
   we.click();
   String result="";
   if(driver.getCurrentUrl().toString().equals("https://eroomrent.in/ownerlogin.php"))
   {
   result = "fail";
   }
   else
   {
   result="pass";
   }
   FileOutputStream fout = new FileOutputStream("d://Testdata1.xlsx"); 
   cell = sheet.getRow(i).createCell(2);
   cell.setCellType(CellType.STRING);
  // sheet.getRow(i).createCell(2).setCellValue("pass"); 
   cell.setCellValue(result);
  
   workbook.write(fout);
   fout.close();
   }
  }
  catch(Exception ex)
  {
  System.out.print(ex.getMessage().toString());
  }
}
@AfterTest
public void TestSetupclose()
{
 driver.close();
}
}
2 Keyword-driven Framework:-


Create an Excel file with this structure


IT Provide Set of Keywords which contains Object, Object Type, Value, and connected with the repository.
step for keyword:-
1 Create Environment using APACHE POI, SELENIUM, TestNG
2 Create ReadExcel class:-
first, create a package then create a class in eclipse:-
package readexcel;
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.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcel {
public Sheet readExcel(String filePath,String fileName,String sheetName) throws IOException{
//Create a object of File class to open xlsx file
File file = new File(filePath+"\\"+fileName);
//Create an object of FileInputStream class to read excel file
FileInputStream inputStream = new FileInputStream(file);
Workbook guru99Workbook = null;
//Find the file extension by spliting file name in substing and getting only extension name
String fileExtensionName = fileName.substring(fileName.indexOf("."));
//Check condition if the file is xlsx file
if(fileExtensionName.equals(".xlsx")){
//If it is xlsx file then create object of XSSFWorkbook class
guru99Workbook = new XSSFWorkbook(inputStream);
}
//Check condition if the file is xls file
else if(fileExtensionName.equals(".xls")){
//If it is xls file then create object of XSSFWorkbook class
guru99Workbook = new HSSFWorkbook(inputStream);
}
//Read sheet inside the workbook by its name
Sheet  guru99Sheet = guru99Workbook.getSheet(sheetName);
return guru99Sheet;
}
}
3)  create objects package and create the file with object.properties and define all object value:-
url=http://newtours.demoaut.com/
username=userName
password=password
loginButton=login


4)  create ReadObject class using operation package:-

package operation;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ReadObject {
Properties p = new Properties();
public Properties getObjectRepository() throws IOException{
//Read object repository file
InputStream stream = new FileInputStream(new File(System.getProperty("user.dir")+"\\src\\objects\\object.properties"));
//load all objects
p.load(stream);
return p;
}
}
create UIOperation.java in the same package:-
package operation;
import java.util.Properties;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class UIOperation {
WebDriver driver;
public UIOperation(WebDriver driver){
this.driver = driver;
}
public void perform(Properties p,String operation,String objectName,String objectType,String value) throws Exception{
System.out.println("");
switch (operation.toUpperCase()) {
case "CLICK":
//Perform click
driver.findElement(this.getObject(p,objectName,objectType)).click();
break;
case "SETTEXT":
//Set text on control
driver.findElement(this.getObject(p,objectName,objectType)).sendKeys(value);
break;
case "GOTOURL":
//Get url of application
driver.get(p.getProperty(value));
break;
case "GETTEXT":
//Get text of an element
driver.findElement(this.getObject(p,objectName,objectType)).getText();
break;

default:
break;
}
}
/**
* Find element BY using object type and value
* @param p
* @param objectName
* @param objectType
* @return
* @throws Exception
*/
private By getObject(Properties p,String objectName,String objectType) throws Exception{
//Find by xpath
if(objectType.equalsIgnoreCase("XPATH")){
return By.xpath(p.getProperty(objectName));
}
else if(objectType.equalsIgnoreCase("ID")){
return By.id(p.getProperty(objectName));
}
//find by class
else if(objectType.equalsIgnoreCase("CLASSNAME")){
return By.className(p.getProperty(objectName));
}
//find by name
else if(objectType.equalsIgnoreCase("NAME")){
return By.name(p.getProperty(objectName));
}
//Find by css
else if(objectType.equalsIgnoreCase("CSS")){
return By.cssSelector(p.getProperty(objectName));
}
//find by link
else if(objectType.equalsIgnoreCase("LINK")){
return By.linkText(p.getProperty(objectName));
}
//find by partial link
else if(objectType.equalsIgnoreCase("PARTIALLINK")){
return By.partialLinkText(p.getProperty(objectName));
}else
{
throw new Exception("Wrong object type");
}
}
}
5)  Create Executor.java file to execute operation using TestNG Class:-
package keyworddriven;
import org.testng.annotations.Test;
import readexcel.ReadExcel;
import operation.*;
import org.testng.annotations.BeforeMethod;
import java.util.Properties;
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.testng.annotations.AfterMethod;
public class ExecuteTest {
WebDriver driver;
@BeforeMethod
  public void beforeMethod() {
System.setProperty("webdriver.chrome.driver", "C://chromedriver.exe");
driver = new ChromeDriver();
  }
  @Test
  public void f() throws Exception {
  ReadExcel file = new ReadExcel();
      ReadObject object = new ReadObject();
      Properties allObjects =  object.getObjectRepository();
      UIOperation operation = new UIOperation(driver);
      Sheet guru99Sheet = file.readExcel(System.getProperty("user.dir")+"\\","TestCase.xlsx" , "KeywordFramework");
      //Find number of rows in excel file
    int rowCount = guru99Sheet.getLastRowNum()-guru99Sheet.getFirstRowNum();
    //Create a loop over all the rows of excel file to read it
    for (int i = 1; i < rowCount+1; i++) {
    //Loop over all the rows
    Row row = guru99Sheet.getRow(i);
    //Check if the first cell contain a value, if yes, That means it is the new testcase name
    if(row.getCell(0).toString().length()==0){
    //Print testcase detail on console
    System.out.println(row.getCell(1).toString()+"----"+ row.getCell(2).toString()+"----"+
    row.getCell(3).toString()+"----"+ row.getCell(4).toString());
    //Call perform function to perform operation on UI
    operation.perform(allObjects, row.getCell(1).toString(), row.getCell(2).toString(),
    row.getCell(3).toString(), row.getCell(4).toString());
        }
    else{
    //Print the new  testcase name when it started
    System.out.println("New Testcase->"+row.getCell(0).toString() +" Started");
    }
    }
  }
  @AfterMethod
  public void afterMethod() {
  }
}
3 Hybrid   Framework:-  

it is a combination of a data-driven and keyword-based framework. if you will combine both examples then it will be called the Hybrid framework.



Post a Comment

3Comments

POST Answer of Questions and ASK to Doubt

  1. you have written an excellent blog.. keep sharing your knowledge...
    Selenium with Python Training
    Selenium with Python Course

    ReplyDelete
  2. event management. Doubling down on becoming the leading networking-focused hybrid event platform and They continue to build an impressive client list that includes some of the largest companies in B2B events. invitation text sample and thank you for the meeting email

    ReplyDelete
  3. event management. Doubling down on becoming the leading networking-focused hybrid event platform and They continue to build an impressive client list that includes some of the largest companies in B2B events. invitation text sample and thank you for the meeting email

    ReplyDelete
Post a Comment