[Selenium+Java] Selenium Framework: Keyword Driven & Hybrid

Original from: https://www.guru99.com/creating-keyword-hybrid-frameworks-with-selenium.html

What is Selenium Framework?

Selenium Framework is a code structure that helps to make code maintenance easy. Without frameworks, we will place the “code” as well as “data” in the same place which is neither re-usable nor readable. Using Frameworks, produce beneficial outcomes like increased code re-usage, higher portability, reduced script maintenance cost, higher code readability, etc.

There are mainly three type of frameworks created by Selenium WebDriver to automate manual test cases

  • Data Driven Test Framework
  • Keyword Driven Test Framework
  • Hybrid Test Framework

Data Driven Test Framework

In data driven framework all of our test data is generated from some external files likeExcel, CSV, XML or some database table. We already learned about Data DrivenTestingin our previous tutorial

Keyword Driven Test Framework:

In keyword driven test framework, all the operations and instructions are written in some external file like Excel worksheet. Here is how the complete framework looks like

As you can see it‘s a 5 step framework. Let‘s study it stepwise in detail

Step 1)

  • The driver script Execute.java will call ReadGuru99ExcelFile.java
  • ReadGuru99ExcelFile.java has POI script to read data from an Excel

Step 2)

  • ReadGuru99ExcelFile.java will read data from TestCase.xlsx
  • Here is how the sheet looks like-

  • According to the keywords written in Excel file, the framework will perform the operation on UI.
  • For example, we need to click a button ‘Login.‘ Correspondingly, our Excel will have a keyword ‘Click.‘ Now the AUT can have hundreds of button on a page, to identify a Login button, in Excel we will input Object Name as loginButton & object type as a name (see highlighted the row in above image). The Object Type could be Xpath, name CSS or any other value

Step 3) ReadGuru99ExcelFile.java will pass this data to the driver script Execute.java

Step 4)

  • For all of our UI web elements, we need to create an object repository where we will place their element locator (like Xpath, name, CSS path, class name etc.)

  • Execute.java (our driver script) will read the entire Object Repository and store it in a variable
  • To read this object repository, we need a ReadObject class which has a getObjectRepository method to read it.

NOTE: You may think why do we need to create an object repository. The answer helps in code maintenance. For example, we are using the button with name = btnlogin in 10 different test cases. In future, the developer decides to change the name from btnlogin to submit. You will have to make a change in all the 10 test cases. In the case of an object repository, you will make the change just once in the repository.

Step 5)

  • The driver will pass the data from Excel & Object Repository to UIOperation class
  • UIOperation class has functions to perform actions corresponding to keywords like CLICK, SETTEXT etc… mentioned in the excel
  • UIOperation class is aJavaclass which has the actual implementation of the code to perform operations on web elements

The complete project will look like-

Let‘s look into an example:

Test Scenario

object.properties

url=http://demo.guru99.com/V4/

username=uid

password=password

title=barone

loginButton=btnLogin

resetButton=btnReset

ReadGuru99ExcelFile.java

package excelExportAndFileIO;
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 ReadGuru99ExcelFile {

    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;
    }
}

ReadObject.java

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;
    }

}

UIOperation.java

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));
        }
        //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");
        }
    }
}

ExecuteTest.java

package testCases;
import java.util.Properties;
import operation.ReadObject;
import operation.UIOperation;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import excelExportAndFileIO.ReadGuru99ExcelFile;
public class ExecuteTest {
@Test
    public void testLogin() throws Exception {
        // TODO Auto-generated method stub
WebDriver webdriver = new FirefoxDriver();
ReadGuru99ExcelFile file = new ReadGuru99ExcelFile();
ReadObject object = new ReadObject();
Properties allObjects = object.getObjectRepository();
UIOperation operation = new UIOperation(webdriver);
//Read keyword sheet
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");
            }
        }
    }
}

After execution, output will look like -

Download the Selenium Project Files for the Demo in this Tutorial

Hybrid Test Framework

Hybrid Test framework is a concept where we are using the advantage of both Keyword and Data driven framework.

Here for keywords, we will use Excel files to maintain test cases, and for test data, we can use data, provider ofTestngframework.

Here in our hybrid framework, we don‘t need to change anything in Keyword driven framework, here we just need to replace ExecuteTest.java file with HybridExecuteTest.java file.

This HybridExecuteTest file has all the code for keyword driven with data provider concept.

The complete pictorial representation of hybrid framework will look like

HybridExecuteTest.java

package testCases;
import java.io.IOException;
import java.util.Properties;
import operation.ReadObject;
import operation.UIOperation;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import excelExportAndFileIO.ReadGuru99ExcelFile;
public class HybridExecuteTest {
    WebDriver webdriver = null;
@Test(dataProvider="hybridData")
    public void testLogin(String testcaseName,String keyword,String objectName,String objectType,String value) throws Exception {
        // TODO Auto-generated method stub

    if(testcaseName!=null&&testcaseName.length()!=0){
    webdriver=new FirefoxDriver();
    }
ReadObject object = new ReadObject();
Properties allObjects = object.getObjectRepository();
UIOperation operation = new UIOperation(webdriver);
    //Call perform function to perform operation on UI
            operation.perform(allObjects, keyword, objectName,
                objectType, value);

    }
@DataProvider(name="hybridData")
    public Object[][] getDataFromDataprovider() throws IOException{
    Object[][] object = null;
    ReadGuru99ExcelFile file = new ReadGuru99ExcelFile();
//Read keyword sheet
Sheet guru99Sheet = file.readExcel(System.getProperty("user.dir")+"\\","TestCase.xlsx" , "KeywordFramework");
//Find number of rows in excel file
    int rowCount = guru99Sheet.getLastRowNum()-guru99Sheet.getFirstRowNum();
    object = new Object[rowCount][5];
    for (int i = 0; i < rowCount; i++) {
        //Loop over all the rows
        Row row = guru99Sheet.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;
    }
}

Summary:

  • We can create three types of test framework using Selenium WebDriver.
  • These are Data Driven, Keyword Driven, and Hybrid test framework.
  • We can achieve Data-driven framework using TestNG‘s data provider.
  • In Keyword driven framework, keywords are written in some external files like excel file and java code will call this file and execute test cases.
  • The hybrid framework is a mix of keyword driven and data driven framework.

原文地址:https://www.cnblogs.com/alicegu2009/p/9080046.html

时间: 2024-10-06 00:03:51

[Selenium+Java] Selenium Framework: Keyword Driven & Hybrid的相关文章

[Selenium+Java] Selenium Grid Tutorial: Command Line and JSON Example

Original URL: https://www.guru99.com/introduction-to-selenium-grid.html What is Selenium Grid? Selenium Grid is a part of the Selenium Suite that specializes in running multiple tests across different browsers, operating systems, and machines in para

[Selenium+Java] Selenium with HTMLUnit Driver &amp; PhantomJS

Original URL: https://www.guru99.com/selenium-with-htmlunit-driver-phantomjs.html HTMLUnitDriver & PhantomJS for Selenium Headless Testing Selenium Web driver is a web automation tool which enables you to run the tests against different browsers. The

java+selenium/java+selenium RC 项目搭建连接整理

手把手__SELENIUM_JAVA搭建_总结汇总篇:http://wenku.baidu.com/link?url=AbZX_o7JoH9Qaz0Q1aSWvTNLzeOwQCaqf_n0wnvbYAXgF9qoYIY6Chhb0hU6m3_sOI8dZ5iwOKThv9R2QQrmxO7yFNDBzpTBZlRFynIDC2q selenium _RC _java环境配置:http://wenku.baidu.com/view/6641fd0f844769eae009ed93.html?re

[Selenium+Java] https://www.guru99.com/using-robot-api-selenium.html

Original URL: https://www.guru99.com/using-robot-api-selenium.html Robot Class in Selenium Webdriver Why Robot Class? In certain Selenium Automation Tests, there is a need to control keyboard or mouse to interact with OS windows like Download pop-up,

Selenium Web 自动化 - Selenium(Java)环境搭建

Selenium Web 自动化 - Selenium(Java)环境搭建 2016-07-29 第1章 Selenium环境搭建 1.1 下载JDK JDK下载地址:http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html 1.2 安装和配置JDK 安装目录尽量不要有空格  D:\Java\jdk1.8.0_91; D:\Java\jre8 设置环境变量: “我的电脑”->右键->“

java+Selenium+TestNg搭建自动化测试架构(1)实现代码和数据的分离

1.主要介绍介绍Java+Selenium+POM的自动化测试框架的搭建,第一个首先实现代码和账号URL等信息的分离.第二点支持跨浏览器,通过读取配置文件的方式实现. 1)将账号URL等信息添加在properties文件中然后读取 2)编写浏览器类通过去取配置文件实现浏览器的切换 3)测试浏览器类 项目结构: 1.新建一个文件夹将properties文件放在文件夹中内容如下: # browser switcher #browserName = FirefoxbrowserName = Chrom

Selenium+Java+Eclipse 自动化测试环境搭建

一.下载Java windows java下载链接 https://www.java.com/zh_CN/download/win10.jsp 二.安装Java 安装好后检查一下需不需要配置环境变量,现在java 8已经不用配置环境变量了,直接在命令行输入:java -version 三.下载和安装Eclipse windows Eclipse下载链接 https://www.eclipse.org/downloads/ 你也可以下载绿色版 四.下载selenium,然后解压 selenium

软件测试之Selenium Java WebDriver

编写Selenium Java WebDriver程序,测试inputgit.csv表格中的学号和git地址的对应关系 package selenium2; import java.util.regex.Pattern; import java.util.concurrent.TimeUnit; import org.junit.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import o

自动化测试框架selenium+java+TestNG——配置篇

最近来总结下自动化测试 selenium的一些常用框架测试搭配,由简入繁,最简单的就是selenium+java+TestNG了,因为我用的是java,就只是总结下java了. TestNG在线安装: 打开Eclipse   Help ->Install New Software ,   然后Add   "http://beust.com/eclipse" 选择TestNG,finish下一步完成安装. 验证是否安装成功 File->new->other 导入sele