Selenium自動化框架:數據驅動、關鍵字驅動和混合

微信公眾號-IT趕路人,專注分享與IT相關知識,關注我,一起升職加薪!

什么是Selenium框架?

這個 Selenium框架 是一種代碼結構,它使代碼維護變得簡單而高效。如果沒有框架,用戶可以將“c”框架產生了一些有益的結果,比如增加了代碼可重用性、更高的可移植性、降低了腳本維護成本、更好的代碼可讀性等。

Selenium WebDriver主要創(chuàng)建了三種類型的框架來自動化手動測試用例

  • 數據驅動測試框架

  • 關鍵字驅動測試框架

  • 混合測試框架


    56.png

Selenium中的數據驅動框架

Selenium中的數據驅動框架 是一種將數據集與測試用例分開的方法。一旦數據集從測試用例中分離出來,就可以很容易它用于從外部文件獲取測試用例和套件,如Excel、.csv、.xml或某些數據庫表。


57.png

為了讀取或寫入Excel,Apache提供了一個非常著名的庫POI。此庫足夠讀寫兩個庫 XLS 和 xlsx Excel的文件格式。

閱讀 XLS 文件,一個 HSSF 實現由POI庫提供。

閱讀 xlsx, XSSF 實現 POI 庫 將是我們的選擇。讓我們詳細研究一下這些實現。

我們已經在我們的上一個教程

Selenium中的關鍵字驅動框架

Selenium中的關鍵字驅動框架 是一種用于通過分隔常用函數和指令集的關鍵字來加速自動化測試的方法。用戶可以輕松地控制和指定他們想要測試的功能。

下面是完整框架的外觀


58.png

如所見,它是一個5步框架。讓我們逐步詳細地研究一下

步驟1)

  • 驅動程序腳本Execute.java將調用ReadGuru99ExcelFile.java

  • ReadGuru99ExcelFile.java具有從Excel讀取數據的POI腳本

步驟2)

  • ReadGuru99ExcelFile.java將從TestCase.xlsx讀取數據

  • 這是床單的樣子-


    59.png
  • 框架將根據Excel文件中寫入的關鍵字對UI進行操作。

  • 例如,我們需要單擊“登錄”按鈕。相應地,我們的Excel將有一個關鍵字“點擊”?,F在AUT可以在一個頁面上有數百個按鈕,為了標識一個登錄按鈕,在Excel中,我們將輸入對象名稱為loginButton,輸入對象類型作為名稱(參見上圖中突出顯示的行)。對象類型可以是XPath、名稱CSS或任何其他值

步驟3) ReadGuru99ExcelFile.java會將此數據傳遞給驅動程序腳本Execute.java

步驟4)

  • 對于所有的UI web元素,我們需要創(chuàng)建一個對象存儲庫,我們將在其中放置它們的元素定位符(如XPath、名稱、CSS路徑、類名等)。


    60.png
  • java(我們的驅動程序腳本)將讀取整個對象存儲庫并將其存儲在一個變量中

  • 要讀取此對象存儲庫,我們需要一個具有getObjectRepository方法的ReadObject類來讀取它。


    61.png

    注: 可能會想,我們?yōu)槭裁葱枰獎?chuàng)建對象存儲庫。對于對象存儲庫,只需在存儲庫中進行一次更改。
    步驟5)

  • 驅動程序會將數據從Excel&Object Repository傳遞到UIOperation類

  • UIOperation類具有執(zhí)行與關鍵字相對應的動作的功能,如CLICK、SETTEXT等…在EXCEL中提到

  • UIOperation類是一個Java語言類,該類具有對web元素執(zhí)行操作的代碼的實際實現。


    62.png

    整個項目將看起來像-


    63.png

    讓我們來看一個例子:

測試場景

object.properties

url= [http://www.itxiaonv.com/V4/](http://www.itxiaonv.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");
            }
        }
    }
}

執(zhí)行后,輸出將如下所示-


64.png

下載本教程中演示的Selenium項目文件

混合框架

混合框架 In Selenium是一個概念,在這個概念中,我們既利用了關鍵字驅動框架的優(yōu)勢,也利用了數據驅動框架的優(yōu)勢。它是一個易于使用的框架,允許手動測試人員只需查看關鍵字、測試數據和對象存儲庫就可以創(chuàng)建測試用例,而無需在框架中編碼。

在這里,對于關鍵字,我們將使用Excel文件來維護測試用例,而對于測試數據,我們可以使用Data、ProviderTestNG框架。


65.png

在我們的混合框架中,我們不需要更改關鍵字驅動框架中的任何內容,這里我們只需要將ExecuteTest.java文件替換為Hybridge ExecuteTest.java文件。


66.png

此Hybridge ExecuteTest文件包含由數據提供程序概念驅動的關鍵字的所有代碼。

混合框架的完整圖示如下所示


67.png

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

總結:

  • 我們可以使用Selenium WebDriver創(chuàng)建三種類型的測試框架。

  • 它們是數據驅動、關鍵字驅動和混合測試框架。

  • 我們可以使用TestNG的數據提供程序來實現數據驅動框架。

  • 在關鍵字驅動框架中,關鍵字被寫入一些外部文件,如EXCEL文件,Java代碼將調用該文件并執(zhí)行測試用例。

  • 該混合框架是關鍵字驅動和數據驅動的混合框架。

26322751-8bd00fde1a719aa1.jpg
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容