0
点赞
收藏
分享

微信扫一扫

JavaSelenium处理Excel数据驱动做测试

木樨点点 2022-08-02 阅读 98

package com.gloryroad.testcase;



import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.util.ArrayList;

import java.util.List;



import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.ss.usermodel.Sheet;

import org.apache.poi.ss.usermodel.Workbook;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;



public class TestDataByExcelFile {

public WebDriver driver;

private String url="http://www.baidu.com";

@BeforeMethod

public void setUp(){

driver=new FirefoxDriver();

driver.get(url);


}



@AfterMethod

public void tearDown(){

driver.close();

}


@DataProvider(name="testData")

public static Object[][] words() throws IOException

{


return getData("C:\\JavaScript\\SeleniumProj\\resuorce", "3.xlsx", "Sheet1");


}


@Test(dataProvider="testData")

public void searchTest(String word1,String word2,String word3){

System.out.println(word1+word2+word3);

driver.findElement(By.id("kw")).sendKeys(word1+" "+word2);



}

/**

* 获取数据

* @throws IOException

*/



public static Object[][] getData(String filePath,String fileName,String sheetName) throws IOException{

//制作File对象

File file=new File(filePath+"\\"+fileName);

FileInputStream input=new FileInputStream(file);

Workbook workbook=null;

//

String fileExtensionName=fileName.substring(fileName.indexOf("."));

if (fileExtensionName.equals(".xlsx")) {

workbook=new XSSFWorkbook(input);


}else if (fileExtensionName.equals(".xls")) {

workbook=new HSSFWorkbook(input);


}


//获取sheet

Sheet sheet=workbook.getSheet(sheetName);

//获取总行数

int row=sheet.getLastRowNum()-sheet.getFirstRowNum();


List<Object[]> records=new ArrayList<Object[]>();

for (int i = 1; i < row+1; i++) {

Row rowValue=sheet.getRow(i);

//声明三个数组用来存储三个数据


String[] fileds=new String[rowValue.getLastCellNum()];


for (int j = 0; j < rowValue.getLastCellNum(); j++) {


fileds[j]=rowValue.getCell(j).getStringCellValue();


}


records.add(fileds);

}


Object[][] results=new Object[records.size()][];

for (int i = 0; i < records.size(); i++) {

results[i]=records.get(i);

}


return results;

}


}

举报

相关推荐

0 条评论