i

Selenium Step By Step Guide

Hybrid Framework Code

We have discussed the Hybrid framework and its creation in detail in previous chapters as well. Let us focus on code part to create the hybrid automation framework:

Add the Excel Reading class to read the excel data:

As we have discussed in previous topics, that excel utility class can be created by using the Apache-Poi library. We need to import the Apache-Poi libraries in our pom.xml file.

<dependency>

    <groupId>org.apache.poigroupId>

    <artifactId>poi-ooxmlartifactId>

    <version>3.12version>

dependency>

We can check the latest version of the same in the maven repository.

Now let us create an excel file that contains the username and password of two different users. Let us see the content of excel file below:

Test

Keyword

Object

ObjectType

Value

Login

 

 

 

 

 

OPENURL

 

 

url

 

ENTERTEXT

Userid

XPATH

user1

 

ENTERTEXT

Password

XPATH

password1

 

CLICK

btnLogin

XPATH

 

 

We can save this file as testData.xlsx and keep it in an accessible file location as we need to pass the file path of this file to read the excel for our data provider.

Let us write see the sample code to read from the Excel. This class is named as “ExcelReading” class:

package TestSuite;

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 ExcelReader {

   

    @SuppressWarnings("resource")

      public Sheet readExcel(String filePath,String fileName,String sheetName) throws IOException{

   

    File file =    new File(filePath+"\\"+fileName);

    FileInputStream inputStream = new FileInputStream(file);

    Workbook workbook = null;

    String fileExtensionName = fileName.substring(fileName.indexOf("."));

    if(fileExtensionName.equals(".xlsx")){

    workbook = new XSSFWorkbook(inputStream);

    }

    else if(fileExtensionName.equals(".xls")){

        workbook = new HSSFWorkbook(inputStream);

    }

    //Read sheet inside the workbook by its name

    Sheet sheet = workbook.getSheet(sheetName);

     return sheet;   

    }

}

 

  1. BaseActions Class:

BaseActions class keeps the logic to perform a the actions which are supplied from the keyword data of the excel file. Let us see the BaseActions class.

package TestSuite;

import java.util.Properties;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

public class BaseActions {

    WebDriver driver;

    public BaseActions(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":

            //Click action on element

            driver.findElement(this.getObject(p,objectName,objectType)).click();

            break;

        case "ENTERTEXT":

            //Enter the text on text boxes

            driver.findElement(this.getObject(p,objectName,objectType)).sendKeys(value);

            break;

           

        case "OPENURL":

            //Open the application url.

            driver.get(p.getProperty(value));

            break;

        case "GETTEXT":

            //Get the text from an element

            driver.findElement(this.getObject(p,objectName,objectType)).getText();

            break;

        default:

            break;

        }

    }

   

    private By getObject(Properties p,String objectName,String objectType) throws Exception{

        //Find the object with xpath

        if(objectType.equalsIgnoreCase("XPATH")){

           

            return By.xpath(p.getProperty(objectName));

        }

        //Find the object with class

        else if(objectType.equalsIgnoreCase("CLASSNAME")){

           

            return By.className(p.getProperty(objectName));

           

        }

        //Find the object with name

        else if(objectType.equalsIgnoreCase("NAME")){

           

            return By.name(p.getProperty(objectName));

           

        }

        //Find the object with css

        else if(objectType.equalsIgnoreCase("CSS")){

           

            return By.cssSelector(p.getProperty(objectName));

           

        }

        //Find the object with link

        else if(objectType.equalsIgnoreCase("LINK")){

           

            return By.linkText(p.getProperty(objectName));

           

        }

        //Find the object with partial link

        else if(objectType.equalsIgnoreCase("PARTIALLINK")){

           

            return By.partialLinkText(p.getProperty(objectName));

           

        }else

        {

            throw new Exception("Wrong object type");

        }

    }

}

  1. ObjectReader Class:

ObjectReader class loads all the object locators and data of a property file. We need to create an ObjectRepo.properties file and keep it in the project directory with below content:

#######---------------Login Page Object----------#########

url=https://selflearning.io/login

userid=//*[@id='admin_login']/div[1]/input

password=//*[@id='admin_login']/div[2]/input

btnLogin=//*[@id="admin_login"]/div[3]/div[2]/input

 

Let us see the ObjectReader class to load this property file:

package TestSuite;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.util.Properties;

public class ObjectReader {

    Properties p = new Properties();

    public Properties getObjectRepository() throws IOException{

        //Read object repository file

        InputStream stream = new FileInputStream(new File(System.getProperty("user.dir")+"\\ObjectRepo.Properties"));

        //load all objects

        p.load(stream);

         return p;

    }

   

}

ObjectReader class has a method getObjectRepository, and it returns an object of Properties type. This Properties object contains all the locators and data of the properties file, and this content is used by the BaseActions class to locate the element to perform the relevant actions on the same.

 

  1. TestNG Class:

Let us create a TestNG class to run the test cases:

package TestSuite;

 

 

import java.io.IOException;

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;

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;

 

public class TestNGTest {

                WebDriver driver;

               

               

                @Test(dataProvider="crendentialData")

    public void testLogin(String testcaseName,String keyword,String objectName,String objectType,String value) throws Exception {

     

    if(testcaseName!=null&&testcaseName.length()!=0){

                System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir"+"/testData.xlsx"));

                                this.driver= new ChromeDriver();

    }

      ObjectReader object = new ObjectReader();

      Properties allObjects = object.getObjectRepository();

      BaseActions operation = new BaseActions(driver);

    //Use of perform method to perform actions on UI

     operation.perform(allObjects, keyword, objectName,

                objectType, value);

   

    }

   

                @DataProvider(name="crendentialData")

    public Object[][] getDataFromDataprovider() throws IOException{

    Object[][] object = null;

    ExcelReader file = new ExcelReader();

    //Reading the sheet for keywords and data

    Sheet sheet = file.readExcel(System.getProperty("user.dir")+"\\","testData.xlsx" , "TestData");

    // Number of rows in excel sheet

    int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum();

    object = new Object[rowCount][5];

    for (int i = 0; i < rowCount; i++) {

        //Loop to read all the rows

        Row row = sheet.getRow(i+1);

        //Create a loop to print cell values in a row

        for (int j = 0; j < row.getLastCellNum(); j++) {

            //Print excel data in console

            object[i][j] = row.getCell(j).toString();

        }

    }

    System.out.println("");

     return object;   

    }

 

                @AfterMethod

                void cleanup()

                {

                                driver.quit();

                }

 

}