我正在尝试在我的 selenium 测试脚本中从 excel 中检索数据。我有一个 excelData 文件,我有我的代码来读取和设置 excel 数据,我有另一个类文件,我从 excel 中获取数据。当我运行我的测试脚本时,它没有返回任何数据。
我的 Excel 代码:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;
public class ExcelUtils {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell Cell;
private static XSSFRow row;
private static MissingCellPolicy xRow;
//This method is to set the File path and to open the Excel file, Pass Excel Path and Sheetname as Arguments to this method
public static void setExcelFile(String Path,String SheetName) throws Exception {
try {
// Open the Excel file
FileInputStream ExcelFile = new FileInputStream(Path);
// Access the required test data sheet
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
} catch (Exception e){
throw (e);
}
}
//This method is to read the test data from the Excel cell, in this we are passing parameters as Row num and Col num
public static String getCellData(int RowNum, int ColNum) throws Exception{
try{
Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
String CellData = Cell.getStringCellValue();
return CellData;
}catch (Exception e){
return"";
}
}
//This method is to write in the Excel cell, Row num and Col num are the parameters
public static void setCellData(String Result, int RowNum, int ColNum) throws Exception {
try{
row = ExcelWSheet.getRow(RowNum);
Cell = row.getCell(ColNum, MissingCellPolicy.RETURN_BLANK_AS_NULL);
if (Cell == null) {
Cell = row.createCell(ColNum);
Cell.setCellValue(Result);
} else {
Cell.setCellValue(Result);
}
// Constant variables Test Data path and Test Data file name
FileOutputStream fileOut = new FileOutputStream(Constants.Path_TestData + Constants.File_TestData);
ExcelWBook.write(fileOut);
fileOut.flush();
fileOut.close();
}catch(Exception e){
throw (e);
}
}
}
我的测试脚本:
import org.openqa.selenium.By;
import org.testng.annotations.Test;
import config.config;
import utility.ExcelUtils;
public class ExcelData extends config {
@Test(priority=0)
public void SignIn() throws Exception {
driver.get("https://www.google.com/");
String SearchData = ExcelUtils.getCellData(1, 1);
driver.findElement(By.name("q")).sendKeys(SearchData);
}
}
这是常量文件:
public class Constants {
public static final String Chrome_Driver = "~/Eclipserelatedfiles/chromedriver_linux64/chromedriver";
public static final String Path_TestData = "~/Documents/eclipse-workspace/Automation/testdata/";
public static final String File_TestData = "TestData.xlsx";
}
Excel文件:
Data
-----------
seleniumhq
我没有得到什么问题,因为我在我试图获取的特定单元格的 excel 中存在数据。任何帮助/建议都会有所帮助。