我是Java Selenium的新手,并尝试从excel文件中获取登录输入作为测试数据(2个登录详细信息)。但是,我无法从excel文件中读取测试数据并使用它来登录。有人可以给我一个代码。
我尝试了以下代码:
import org.testng.annotations.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
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.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.BeforeTest;
public class Sample1 {
WebDriver driver;
WebDriverWait wait;
XSSFWorkbook workbook;
XSSFSheet sheet;
XSSFCell cell;
@Test
public void f() throws IOException {
File src=new File("C:\\Standalone\\TestData.xls");
FileInputStream finput = new FileInputStream(src);
workbook = new XSSFWorkbook(finput);
sheet= workbook.getSheetAt(0);
for(int i=1; i<=sheet.getLastRowNum();i++)
{
cell = sheet.getRow(i).getCell(1);
cell.setCellType(Cell.CELL_TYPE_STRING);
driver.findElement(By.id("j_username")).sendKeys(cell.getStringCellValue());
cell = sheet.getRow(i).getCell(2);
cell.setCellType(Cell.CELL_TYPE_STRING);
driver.findElement(By.id("j_password")).sendKeys(cell.getStringCellValue());
}
}
@BeforeTest
public void beforeTest() {
System.setProperty("webdriver.chrome.driver","C:\\Chrome\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("c");
}
}
答案 0 :(得分:0)
我建议采用一种非常简单的方法。根据给定的单元格数创建一个Class来读取值
e.g。 ExcelFileReader.java
public class ExcelFileReader
{
FileInputStream fis;
XSSFWorkbook workbook;
XSSFSheet sheet;
public ExcelFileReader() throws IOException
{
// Read Excel File
fis = new FileInputStream(new File("src/test/resources/SiteTestData.xlsx"));
workbook = new XSSFWorkbook(fis);
// To get Sheet 1
sheet = workbook.getSheetAt(0);
}
public String getCellData(int rowNum, int colNum)
{
return sheet.getRow(rowNum).getCell(colNum).getStringCellValue();
}
}
现在,在您的测试方法中调用{/ 1}}方法,如
getCellData