Selenium 框架:数据、关键词和混合驱动

⚡ 智能摘要

Selenium Framework: Data, Keyword, and Hybrid Driven approaches define how testers organize automation code, separate test data, and reuse logic. This article explains each framework type, its architecture, advantages, and how to implement them step-by-step with practical Selenium WebDriver code examples.

  • 核心定义: A Selenium framework is a structured code architecture that improves reusability, portability, and maintenance of automated test scripts.
  • 📊 Data Driven Implementation: Separate test data from logic using Excel, CSV, or XML, and read inputs through Apache POI (HSSF for XLS, XSSF for XLSX).
  • ???? Keyword Driven Design: Drive UI actions through keyword sheets and object repositories so manual testers can build cases without writing Java 码。
  • ⚙️ 混合优化: 结合 TestNG data providers with keyword execution to gain flexibility, scalability, and lower script maintenance overhead.
  • 🧩 Object Repository Benefit: Centralize locators in a properties file so element changes require updating only one location across all test cases.

Selenium 骨架

什么是 Selenium 框架?

Selenium 自动化框架 is a structured code architecture that makes test maintenance simple, scalable, and efficient. Without a framework, testers often place code and data in the same location, which is neither reusable nor readable. Adopting a framework delivers measurable benefits such as higher code reusability, better portability, reduced script maintenance cost, improved readability, and clearer separation of concerns between test logic and input data.

为什么使用 Selenium Automation Framework?

一个精心设计的 Selenium framework solves three persistent problems in test automation: duplication of code, fragile locators, and unmanageable test data. By enforcing a clear structure, teams can scale their suites from a handful of scripts to hundreds without losing control.

  • 可维护性: Centralized locators and helper methods mean a single change updates every test that uses that element.
  • 可重用性: Common operations such as login, navigation, or form entry are written once and invoked across many test cases.
  • 可扩展性: Adding new test cases becomes a data update rather than a coding task, which lets non-developers contribute scenarios.
  • Reporting and Collaboration: Standardized structure makes it easier to integrate with reporting tools, CI/CD pipelines, and version control.

有哪些 Selenium 骨架

主要有以下三个 types of frameworks 建立在 Selenium WebDriver to automate manual test cases. Each style targets a different balance between developer effort, tester involvement, and data flexibility.

  • 数据驱动框架
  • 关键字驱动框架
  • 混合驱动框架

有哪些 Selenium 骨架

The next sections explain each framework in detail, starting with the simplest data-driven approach and progressing to the most flexible hybrid model.

数据驱动框架 Selenium

数据驱动框架 Selenium is a method of separating test data sets from the test case logic. Once the data is decoupled, you can modify inputs for a particular functionality without touching the test code. It is commonly used to fetch test cases and suites from external sources such as Excel, .csv, .xml, or database tables.

数据驱动框架 Selenium

To read or write Excel files, Apache provides the well-known POI library. This library can handle both XLSXLSX 格式。 的 高速SF implementation reads legacy XLS files, while the 跨系统安全框架 implementation handles modern XLSX files.

We already covered Data Driven Testing in our 先前的教程.

关键字驱动框架 Selenium

关键字驱动框架 Selenium is a method that accelerates automation by separating keywords for common functions and instructions. All operations and instructions are written in an external file, typically an Excel sheet. Testers can specify the functionalities they want to validate without modifying Java code, which makes this style ideal for teams where business analysts or manual QA contribute test definitions.

Here is how the complete framework looks:

关键字驱动框架 Selenium

As you can see, it is a 5-step framework. Let us study it stepwise in detail.

步骤1)

  • The driver script Execute.java calls ReadGuru99ExcelFile.java.
  • 了解 Guru99ExcelFile.java contains POI code that reads data from Excel.

步骤2)

  • 了解 Guru99ExcelFile.java reads data from TestCase.xlsx.
  • Here is how the sheet looks:

Keyword Driven Framework Excel sheet in Selenium

  • Based on the keywords written in the Excel file, the framework performs the corresponding action on the UI.
  • For example, to click a button labeled “Login”, the Excel sheet stores the keyword “Click”. To identify the Login button among many on a page, the Excel row defines Object Name as loginButton and Object Type as name (see the highlighted row in the image). The Object Type can also be XPath, CSS, class, or any other locator strategy.

步骤3) 了解 Guru99ExcelFile.java passes the parsed data back to the driver script Execute.java.

步骤4)

  • For all UI web elements, you maintain an object repository that stores element locators such as XPath, name, CSS, or class name.

Object repository in Keyword Driven Framework

  • Execute.java (the driver script) reads the entire object repository and stores it in a variable.
  • A helper ReadObject class exposes a getObjectRepository method that loads the repository at runtime.

ReadObject helper class for Keyword Driven Framework

注意: You may wonder why an object repository is required. The answer is maintainability. If a button with name = btnlogin is used in 10 test cases and the developer renames it to submit, you would otherwise edit 10 files. With an object repository, you change the locator in one place.

步骤5)

  • The driver passes data from Excel and the object repository to the UIOperation class。
  • UIOperation contains functions that map each keyword such as CLICK and SETTEXT to a concrete WebDriver action.
  • UIOperation is a Java class that holds the real implementation for interacting with web elements.

UIOperation class in Keyword Driven Framework

The complete project structure looks like:

Complete project structure of Keyword Driven Framework

Let us look at a practical example:

测试场景: We are executing 2 test cases.

对象.属性

url=https://demo.guru99.com/V4/
username=uid
password=password
title=barone
loginButton=btnLogin
resetButton=btnReset

了解 Guru99ExcelFile.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 File object to open the xlsx file
        File file = new File(filePath + "\\" + fileName);
        // Create a FileInputStream to read the Excel file
        FileInputStream inputStream = new FileInputStream(file);
        Workbook guru99Workbook = null;
        // Detect the file extension
        String fileExtensionName = fileName.substring(fileName.indexOf("."));
        if (fileExtensionName.equals(".xlsx")) {
            guru99Workbook = new XSSFWorkbook(inputStream);
        } else if (fileExtensionName.equals(".xls")) {
            guru99Workbook = new HSSFWorkbook(inputStream);
        }
        // Read the sheet inside the workbook by its name
        Sheet guru99Sheet = guru99Workbook.getSheet(sheetName);
        return guru99Sheet;
    }
}

读取对象.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 the 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;
    }
}

UIOpera函数

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":
                driver.findElement(this.getObject(p, objectName, objectType)).click();
                break;
            case "SETTEXT":
                driver.findElement(this.getObject(p, objectName, objectType)).sendKeys(value);
                break;
            case "GOTOURL":
                driver.get(p.getProperty(value));
                break;
            case "GETTEXT":
                driver.findElement(this.getObject(p, objectName, objectType)).getText();
                break;
            default:
                break;
        }
    }

    private By getObject(Properties p, String objectName, String objectType) throws Exception {
        if (objectType.equalsIgnoreCase("XPATH")) {
            return By.xpath(p.getProperty(objectName));
        } else if (objectType.equalsIgnoreCase("CLASSNAME")) {
            return By.className(p.getProperty(objectName));
        } else if (objectType.equalsIgnoreCase("NAME")) {
            return By.name(p.getProperty(objectName));
        } else if (objectType.equalsIgnoreCase("CSS")) {
            return By.cssSelector(p.getProperty(objectName));
        } else if (objectType.equalsIgnoreCase("LINK")) {
            return By.linkText(p.getProperty(objectName));
        } else if (objectType.equalsIgnoreCase("PARTIALLINK")) {
            return By.partialLinkText(p.getProperty(objectName));
        } else {
            throw new Exception("Wrong object type");
        }
    }
}

执行测试.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 {
        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 the number of rows in the Excel file
        int rowCount = guru99Sheet.getLastRowNum() - guru99Sheet.getFirstRowNum();
        for (int i = 1; i < rowCount + 1; i++) {
            Row row = guru99Sheet.getRow(i);
            if (row.getCell(0).toString().length() == 0) {
                System.out.println(row.getCell(1).toString() + "----" + row.getCell(2).toString() + "----" +
                        row.getCell(3).toString() + "----" + row.getCell(4).toString());
                operation.perform(allObjects, row.getCell(1).toString(), row.getCell(2).toString(),
                        row.getCell(3).toString(), row.getCell(4).toString());
            } else {
                System.out.println("New Testcase->" + row.getCell(0).toString() + " Started");
            }
        }
    }
}

After execution, the output looks like:

Keyword Driven Framework execution output

下载 Selenium 本教程中演示的项目文件

混合驱动框架

混合驱动框架 in Selenium combines the strengths of both Keyword Driven and Data Driven frameworks. It is an easy-to-use model that allows manual testers to create test cases simply by editing keywords, test data, and the object repository, without writing any framework code.

Here, Excel files maintain the keywords for each step, and TestNG“ 数据提供者 supplies the test data. This split lets you scale both the action vocabulary and the input variations independently.

Hybrid Driven Framework architecture

For our hybrid framework, nothing changes in the keyword-driven structure: we simply replace ExecuteTest.java with HybridExecuteTest.java.

Hybrid Driven Framework component replacement

This HybridExecuteTest file contains the full keyword-driven logic combined with TestNG’s data provider mechanism.

The complete pictorial representation of the hybrid framework looks like this:

Hybrid Driven Framework complete representation

混合执行测试.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 {
        if (testcaseName != null && testcaseName.length() != 0) {
            webdriver = new FirefoxDriver();
        }
        ReadObject object = new ReadObject();
        Properties allObjects = object.getObjectRepository();
        UIOperation operation = new UIOperation(webdriver);
        operation.perform(allObjects, keyword, objectName, objectType, value);
    }

    @DataProvider(name = "hybridData")
    public Object[][] getDataFromDataprovider() throws IOException {
        Object[][] object = null;
        ReadGuru99ExcelFile file = new ReadGuru99ExcelFile();
        Sheet guru99Sheet = file.readExcel(System.getProperty("user.dir") + "\\", "TestCase.xlsx", "KeywordFramework");
        int rowCount = guru99Sheet.getLastRowNum() - guru99Sheet.getFirstRowNum();
        object = new Object[rowCount][5];
        for (int i = 0; i < rowCount; i++) {
            Row row = guru99Sheet.getRow(i + 1);
            for (int j = 0; j < row.getLastCellNum(); j++) {
                object[i][j] = row.getCell(j).toString();
            }
        }
        System.out.println("");
        return object;
    }
}

下载 Selenium 本教程中演示的项目文件

常见问题

Choose Keyword Driven when manual testers need to build cases without coding. Choose Data Driven when the same script must run against many input variations. Use Hybrid when you require both data flexibility and keyword-level test authoring at the same time.

Apache POI reads and writes Excel files used as the data source. HSSF handles legacy .xls files, while XSSF processes modern .xlsx files. Together they let your test scripts pull dynamic inputs from spreadsheets without hardcoding data.

An object repository centralizes element locators such as XPath, CSS, or name. If a developer renames a UI control, you update one entry rather than every test case, which dramatically lowers maintenance time and the risk of broken scripts.

人工智能改善 Selenium frameworks through self-healing locators, intelligent test prioritization, and visual validation. AI engines detect locator drift, recommend stable selectors, and analyze failure patterns, which keeps hybrid suites reliable as the application under test evolves.

Yes. Modern AI assistants analyze the application under test and propose keyword libraries, sample inputs, and edge cases. Testers review and refine the suggestions, which accelerates framework setup while keeping human oversight on critical validation logic.

总结一下这篇文章: