• Selenium Video Tutorials

Selenium - 資料驅動框架



Selenium Webdriver 可用於開發基於資料驅動框架的測試指令碼。資料驅動框架主要用於建立依賴於外部資料來源資料的測試用例。此外部資料來源可以是任何具有 .txt、.properties、.xlsx、.xls、.csv 副檔名的檔案,也可以藉助資料提供者。

資料驅動框架是一種將測試用例與資料集分離的框架。此外,它還提供了針對多個數據集運行同一測試用例的功能。由於測試程式碼實現和測試資料彼此獨立,因此可以在不影響實現邏輯的情況下修改資料集,反之亦然。

為什麼要使用資料驅動測試框架?

在資料驅動測試框架中,可以針對同一測試用例執行多個數據集,因此可以在無需額外程式碼的情況下針對廣泛的資料範圍測試同一應用程式。因此,程式碼只需開發一次即可重複使用多次。

資料驅動測試框架允許多次執行測試用例,而無需增加測試用例的數量。有時,測試資料會自動生成,這允許應用程式針對廣泛的隨機資料集進行測試。在這種情況下,資料驅動測試框架確保產品更健壯和高質量。

資料驅動測試框架的優勢

資料驅動測試框架透過確保更結構化的執行來實現測試用例的最佳利用。這也有助於縮短測試周期,同時確保產品質量。包含各種函式、方法和操作的測試實現程式碼在資料驅動測試框架中使用廣泛的資料集進行測試。

資料驅動測試框架與關鍵字驅動測試框架的區別

資料驅動框架和關鍵字驅動框架之間存在一些差異。關鍵字驅動框架更容易維護,因為在測試資料、關鍵字和實現邏輯層之間存在更多抽象,而資料驅動框架比關鍵字驅動框架更難以維護,因為抽象只存在於測試資料和測試指令碼之間。

與資料驅動框架相比,關鍵字驅動框架需要更系統的規劃,因為在資料驅動框架中,我們只是將測試資料與測試指令碼分離。

示例 1 - 使用 Excel 進行資料驅動

讓我們舉一個使用 Apache POI 庫使用 Excel 執行資料驅動測試的例子。讓我們以名為 **DetailsStudent.xlsx** 的 Excel 檔案為例,我們將從該 Excel 檔案中讀取值並將這些資料輸入到下面的註冊頁面,成功後,我們將在單元格(同一行和 E 列)中寫入文字 **測試用例:透過**。如果未成功,我們將在同一單元格中寫入文字 **測試用例:失敗**。

Selenium Data Driven Framework 1

下圖顯示了註冊頁面,我們將在此頁面中從 **DetailsStudent.xlsx** 檔案中輸入 **全名:**、**姓氏:**、**使用者名稱:** 和 **密碼** 欄位中的資料。 成功後,我們將在單元格(同一行和 E 列)中寫入文字 **測試用例:透過**。如果未成功,我們將在同一單元格中寫入文字 **測試用例:失敗**。

Selenium Data Driven Framework 2

**請注意** - **DetailsStudent.xlsx** Excel 檔案放置在專案下的 **Resources** 資料夾中,如下圖所示。

Selenium Data Driven Framework 3

如何安裝 Apache POI?

**步驟 1** - 從以下連結新增 Apache POI Common 依賴項 -

https://mvnrepository.com/artifact/org.apache.poi/poi.

**步驟 2** - 從以下連結新增基於 OPC 和 OOXML 架構的 Apache POI API 依賴項 -

https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml.

**步驟 3** - 儲存包含所有依賴項的 pom.xml 並更新 Maven 專案。

**ExcelReadWrite.java** 中的程式碼實現

package org.example;

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.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class ExcelReadWrite {
   public static  void main(String args[]) throws IOException {
      
      // identify location of .xlsx file
      File f = new File("./Resources/DetailsStudent.xlsx");
      FileInputStream i = new FileInputStream(f);

      // instance of XSSFWorkbook
      XSSFWorkbook w = new XSSFWorkbook(i);

      // create sheet in XSSFWorkbook with name Details1
      XSSFSheet s = w .getSheet("Details1");

      // handle total rows in XSSFSheet
      int r = s.getLastRowNum() - s.getFirstRowNum();

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

      // Opening the webpage where we will identify elements
      driver.get("https://tutorialspoint.tw/selenium/practice/register.php#");

      //Identify elements for registration
      WebElement fname = driver.findElement(By.xpath("//*[@id='firstname']"));
      WebElement lname = driver.findElement(By.xpath("//*[@id='lastname']"));
      WebElement uname = driver.findElement(By.xpath("//*[@id='username']"));
      WebElement pass = driver.findElement(By.xpath("//*[@id='password']"));
      WebElement btn = driver.findElement(By.xpath("//*[@id='signupForm']/div[5]/input"));

      // loop through rows, read and enter values in form
      for(int j = 1; j <= r; j++) {
         fname.sendKeys(s.getRow(j).getCell(0).getStringCellValue());
         lname.sendKeys(s.getRow(j).getCell(1).getStringCellValue());
         uname.sendKeys(s.getRow(j).getCell(2).getStringCellValue());
         pass.sendKeys(s.getRow(j).getCell(3).getStringCellValue());

         // submit registration form
         btn.click();

         // verify form submitted
         WebElement fname1 = driver.findElement(By.xpath("//*[@id='firstname']"));
         String value = fname1.getAttribute("value");

         // create cell at Column 4 to write values in excel
         XSSFCell c = s.getRow(j).createCell(4);

         // write results in excel
         if (value.isEmpty()) {
            c.setCellValue("Test Case: PASS");
         } else {
            c.setCellValue("Test Case: FAIL");
         }

         // complete writing value in excel
         FileOutputStream o = new FileOutputStream("./Resources/DetailsStudent.xlsx");
         w.write(o);
      }

      // closing workbook object
      w.close();

      // Quitting browser
      driver.quit();
   }
}

新增到 pom.xml 的依賴項。

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
   
   <modelVersion>4.0.0</modelVersion>
   <groupId>org.example</groupId>
   <artifactId>SeleniumJava</artifactId>
   <version>1.0-SNAPSHOT</version>
   
   <properties>
      <maven.compiler.source>16</maven.compiler.source>
      <maven.compiler.target>16</maven.compiler.target>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>
   
   <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
   <dependencies>
      <dependency>
         <groupId>org.seleniumhq.selenium</groupId>
         <artifactId>selenium-java</artifactId>
         <version>4.11.0</version>
      </dependency>

      <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
      <dependency>
         <groupId>org.apache.poi</groupId>
         <artifactId>poi</artifactId>
         <version>5.2.5</version>
      </dependency>
      
      <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
      <dependency>
         <groupId>org.apache.poi</groupId>
         <artifactId>poi-ooxml</artifactId>
         <version>5.2.5</version>
      </dependency>
   </dependencies>
</project>

輸出

Process finished with exit code 0

在上面的示例中,我們讀取了整個 Excel 檔案,並在第五列的單元格中寫入值 **測試用例:透過**。

最後,收到訊息 **Process finished with exit code 0**,表示程式碼成功執行。

Selenium Data Driven Framework 4

如上圖所示,在測試執行後,**測試用例:透過** 被寫入 **DetailsStudent.xlsx** Excel 檔案的第 5 列中,這與 Excel 中提供的註冊資料有關。

示例 2 - 使用 TestNG DataProvider 進行資料驅動

讓我們舉一個使用 TestNG 的預設功能(稱為 DataProvider)進行資料驅動測試的例子。DataProvider 用於向任何測試方法提供資料。

我們將使用 TestNG DataProvider 在與前面示例相同的註冊頁面中輸入值,在該頁面中,我們將使用 TestNG DataProvider 輸入 **全名:**、**姓氏:**、**使用者名稱:** 和 **密碼** 欄位中的資料。

如何安裝 TestNG?

  • 在系統中安裝 Java(版本高於 8),並使用命令:java -version 檢查它是否存在。如果安裝已成功完成,則將顯示已安裝的 Java 版本。

  • 在系統中安裝 Maven,並使用命令:mvn -version 檢查它是否存在。如果安裝已成功完成,則將顯示已安裝的 Maven 版本。

  • 安裝任何 IDE,例如 Eclipse、IntelliJ 等。

  • 從以下連結新增 TestNG 依賴項:https://mvnrepository.com/artifact/org.testng/testng

**DataTest.java** 中的程式碼實現

package CrossBrw;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.*;
import java.util.concurrent.TimeUnit;

public class DataTest {
   WebDriver driver;
   @BeforeTest
   public void setup() throws Exception {

      // Initiate the Webdriver
      driver = new ChromeDriver();

      // adding implicit wait of 12 secs
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

      // Opening the webpage
      driver.get("https://tutorialspoint.tw/selenium/practice/register.php#");
   }

   @Test(dataProvider = "registration-data")
   public void userRegistration
   (String fname1, String lname1, String uname1, String pass1) {

      //Identify elements for registration
      WebElement fname = driver.findElement(By.xpath("//*[@id='firstname']"));
      WebElement lname = driver.findElement(By.xpath("//*[@id='lastname']"));
      WebElement uname = driver.findElement(By.xpath("//*[@id='username']"));
      WebElement pass = driver.findElement(By.xpath("//*[@id='password']"));

      // enter details from data provider
      fname.sendKeys(fname1);
      lname.sendKeys(lname1);
      uname.sendKeys(uname1);
      pass.sendKeys(pass1);

      // get values entered
      String text = fname.getAttribute("value");
      String text1 = lname.getAttribute("value");
      String text2 = uname.getAttribute("value");
      String text3 = pass.getAttribute("value");

      System.out.println("Entered first name: " + text);
      System.out.println("Entered last name: " + text1);
      System.out.println("Entered username: " + text2);
      System.out.println("Entered password: " + text3);
   }
   @DataProvider (name = "registration-data")
   public Object[][] registrationData(){
      return new Object[][]
      { {"Ram", "Ganesh", "ABC", "Password12"} };
   }
   @AfterTest
   public void teardown() {
   
      // quitting browser
      driver.quit();
   }
}

新增到 pom.xml 的依賴項。

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
   
   <modelVersion>4.0.0</modelVersion>
   <groupId>org.example</groupId>
   <artifactId>SeleniumJava</artifactId>
   <version>1.0-SNAPSHOT</version>
   
   <properties>
      <maven.compiler.source>16</maven.compiler.source>
      <maven.compiler.target>16</maven.compiler.target>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>
   
   <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
   <dependencies>
      <dependency>
         <groupId>org.seleniumhq.selenium</groupId>
         <artifactId>selenium-java</artifactId>
         <version>4.11.0</version>
      </dependency>
      
      <!-- https://mvnrepository.com/artifact/org.testng/testng -->
      <dependency>
         <groupId>org.testng</groupId>
         <artifactId>testng</artifactId>
         <version>7.9.0</version>
         <scope>test</scope>
      </dependency>
   </dependencies>
</project>

輸出

Entered first name: Ram
Entered last name: Ganesh
Entered username: ABC
Entered password: Password12

===============================================
Default Suite
Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
===============================================

Process finished with exit code 0

在上面的示例中,我們從 DataProvider 中提供的資料中在註冊頁面輸入資料,並在控制檯中獲得輸入的值以及訊息 - **輸入的姓名:Ram,輸入的姓氏:Ganesh,輸入的使用者名稱:ABC** 和 **輸入的密碼:Password12**。

控制檯中的結果顯示 **Total tests run: 1**,因為只有一個方法帶有 @Test 註解 - userRegisterration()。

最後,收到訊息 **Passes: 1** 和 **Process finished with exit code 0**,表示程式碼成功執行。

本教程全面介紹了 Selenium Webdriver - 資料驅動框架。我們首先介紹什麼是資料驅動框架,為什麼要使用資料驅動框架,資料驅動框架的優勢是什麼,資料驅動框架與關鍵字驅動框架的區別是什麼,並透過示例演示瞭如何使用 Excel 和 TestNG 中的 DataProvider 以及 Selenium Webdriver 實現資料驅動框架。

這使您掌握了 Selenium Webdriver 中資料驅動框架的深入知識。明智的做法是繼續練習您所學到的內容,並探索與 Selenium 相關的其他內容,以加深您的理解並擴充套件您的視野。

廣告