17370845950

如何正确读取 Excel 文件实现 Selenium 数据驱动测试

本文详解修复 apache poi 读取 excel 时因文件扩展名判断错误导致的 `nullpointerexception`,并提供健壮、可复用的数据驱动测试代码,涵盖 `.xls`/`.xlsx` 兼容处理、空单元格防护、资源释放及最佳实践。

在使用 Apache POI 实现 Selenium 数据驱动自动化测试时,一个常见却极易被忽视的错误是文件扩展名字符串匹配不准确,这将直接导致 Workbook 对象初始化失败,进而引发 NullPointerException ——正如您遇到的错误:

java.lang.NullPointerException: Cannot invoke "org.apache.poi.ss.usermodel.Workbook.getSheet(String)" because "loginWorkbook" is "null"

根本原因在于 readExcel() 方法中对 .xls 扩展名的判断逻辑存在硬编码缺陷:

else if(fileExtension.equals("xls")) // ❌ 错误:缺少前导点号

由于 fileName.substring(fileName.indexOf(".")) 返回的是类似 ".xls" 或 ".xlsx" 的完整扩展名(含英文句点),而代码中却错误地与 "xls"(无点)比较,导致条件始终为 false,loginWorkbook 保持 null,后续调用 getSheet() 必然崩溃。

✅ 正确写法应为:

else if (fileExtension.equalsIgnoreCase(".xls"))

同时,为提升健壮性与可维护性,我们建议对原始代码进行以下关键优化:

✅ 完整修正版(含增强功能)

package com.framework;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.Duration;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class DataDriveFramework {

    public void readExcel(String file

Path, String fileName, String sheetName) throws IOException { File file = new File(filePath + File.separator + fileName); // 使用 File.separator 提升跨平台兼容性 if (!file.exists()) { throw new IOException("Excel file not found: " + file.getAbsolutePath()); } FileInputStream fis = null; Workbook workbook = null; try { fis = new FileInputStream(file); String fileExtension = fileName.substring(fileName.lastIndexOf(".")).toLowerCase(); if (fileExtension.equals(".xlsx")) { workbook = new XSSFWorkbook(fis); } else if (fileExtension.equals(".xls")) { workbook = new HSSFWorkbook(fis); } else { throw new IllegalArgumentException("Unsupported file format: " + fileExtension); } Sheet sheet = workbook.getSheet(sheetName); if (sheet == null) { throw new IllegalArgumentException("Sheet not found: " + sheetName); } int firstRowNum = sheet.getFirstRowNum(); int lastRowNum = sheet.getLastRowNum(); // 从第1行开始(跳过表头),确保行存在且非空 for (int i = firstRowNum + 1; i <= lastRowNum; i++) { Row row = sheet.getRow(i); if (row == null) continue; // 跳过空行 // 安全读取单元格:处理 null、blank 和不同数据类型 String username = getCellStringValue(row.getCell(0)); String password = getCellStringValue(row.getCell(1)); // ⚠️ 注意:原代码误用 getCell(0) 两次! if (username != null && !username.trim().isEmpty() && password != null && !password.trim().isEmpty()) { test(username, password); } } } finally { // 确保资源释放 if (fis != null) fis.close(); if (workbook != null) workbook.close(); } } // 辅助方法:安全获取字符串值,兼容 STRING、NUMERIC、BLANK 等类型 private String getCellStringValue(Cell cell) { if (cell == null) return null; switch (cell.getCellType()) { case STRING: return cell.getStringCellValue().trim(); case NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { return cell.getDateCellValue().toString(); } else { return String.valueOf((long) cell.getNumericCellValue()).trim(); } case BLANK: return ""; default: return cell.toString().trim(); } } public void test(String username, String password) { WebDriver driver = new FirefoxDriver(); try { driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10)); driver.get("https://accounts.google.com"); // 更稳定的定位方式(避免绝对XPath) driver.findElement(By.id("identifierId")).sendKeys(username); driver.findElement(By.id("identifierNext")).click(); // 替换为语义化ID // 显式等待密码框出现(推荐配合 WebDriverWait) Thread.sleep(2000); // 简化示例,生产环境请用 WebDriverWait driver.findElement(By.name("Passwd")).sendKeys(password); // 改用 name 属性更稳定 driver.findElement(By.id("passwordNext")).click(); // 可添加断言验证登录成功(如检查URL或元素) Thread.sleep(3000); } catch (Exception e) { e.printStackTrace(); } finally { driver.quit(); // 每次测试后关闭浏览器 } } public static void main(String[] args) throws IOException { DataDriveFramework framework = new DataDriveFramework(); String filePath = "C:\\Users\\Shefali\\eclipse-workspace\\DataDriveFramework\\TestExcelSheet\\"; framework.readExcel(filePath, "DataDriven.xls", "Sheet1"); } }

? 关键改进说明

  • ✅ 修复核心 Bug:".xls" 字符串严格匹配,避免 loginWorkbook 为 null;
  • ✅ 安全单元格读取:getCellStringValue() 处理 null、空、数字、日期等类型,防止 NullPointerException 或 IllegalStateException;
  • ✅ 资源自动释放:try-finally 确保 FileInputStream 和 Workbook 正确关闭;
  • ✅ 健壮性增强:校验文件存在、Sheet 存在、跳过空行、过滤空用户名/密码;
  • ✅ 定位策略优化:避免脆弱的绝对 XPath,优先使用 id/name 等稳定属性;
  • ✅ 跨平台兼容:使用 File.separator 替代硬编码 "\\";
  • ✅ 异常明确提示:对不支持格式、缺失 Sheet 等场景抛出清晰异常。

⚠️ 注意事项(务必遵守)

  • 不要在循环内反复创建/销毁 WebDriver:当前示例为简化演示;真实项目应使用 @BeforeMethod/@AfterMethod(TestNG)或 BeforeEach/AfterEach(JUnit5)统一管理 driver 生命周期,或采用线程安全的 ThreadLocal
  • 禁止硬编码测试 URL 和凭证:敏感信息应通过 Properties、YAML 或环境变量注入;
  • 避免 Thread.sleep():生产环境必须改用 WebDriverWait 配合 ExpectedConditions 实现智能等待;
  • Excel 文件需保持打开状态?否! 运行测试前请确保 Excel 文件未被其他程序(如 Excel 应用)独占锁定,否则 FileInputStream 会抛出 IOException。

通过以上修正与增强,您的数据驱动框架将具备生产级稳定性与可维护性。记住:一个健壮的自动化框架,始于对每一个 null 的敬畏,成于对每一处资源的负责。