1. 程式人生 > >資料驅動測試三:使用TestNG、Apache POI和Excel檔案進行資料驅動

資料驅動測試三:使用TestNG、Apache POI和Excel檔案進行資料驅動

一、測試環境準備

1、從http://www.apache.org/dyn/closer.cgi/poi/release/bin/poi-bin/poi-bin-3.14.zip下載POI的壓縮包檔案。

2、將壓縮包進行解壓,將解壓檔案根目錄下的JAR檔案和ooxml-lib資料夾、lib資料夾下的所有JAR檔案均加入到Eclipse的Build Path中。

二、使用TestNG、Apache POI和Excel檔案進行資料驅動

將資料存入Excel檔案的一種資料驅動方式,參考程式碼如下:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

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.XSSFCell;
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.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class TestDataByExcelFile {
	private static WebDriver driver;
	@DataProvider(name="searchData")
	public static Object[][] data() throws IOException
	{
		return getSearchData("E:\\AutoData\\","testData.xlsx","testData");//獲取Excel檔案的測試資料
	}
  @Test(dataProvider="searchData")
  public void testSearch(String searchdata1,String searchdata2,String searchResult) {
	  //開啟sogou首頁
	  driver.get("http://www.sogou.com/");
	  //輸入搜尋條件
	  //從Excel檔案中讀取每行中前2個單元格內容作為搜尋框中輸入的搜尋關鍵詞,在兩個搜尋詞中間增加一個空格
	  driver.findElement(By.id("query")).sendKeys(searchdata1+" "+searchdata2);
	  //單擊搜尋按鈕
	  driver.findElement(By.id("stb")).click();
	  
	  //使用顯式等待方式,確認頁面已經載入完成,頁面底部的關鍵字"搜尋幫助"已經顯示在頁面上
	  (new WebDriverWait(driver,3)).until(new ExpectedCondition<Boolean>(){

		@Override
		public Boolean apply(WebDriver d) {
			return d.findElement(By.id("sogou_webhelp")).getText().contains("搜尋幫助");
		}});

	  //斷言搜尋結果頁面是否包含Excel檔案中每行的最後一個單元格內容的關鍵字
	  Assert.assertTrue(driver.getPageSource().contains(searchResult));
  }
  @BeforeMethod
  public void beforeMethod() {
	  //若無法開啟Firefox瀏覽器,可設定Firefox瀏覽器的安裝路徑
	  System.setProperty("webdriver.firefox.bin", "D:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
	  //開啟Firefox瀏覽器
	  driver=new FirefoxDriver();
	  //設定等待時間為5秒
	  driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
  }

  @AfterMethod
  public void afterMethod() {
	  //關閉開啟的瀏覽器
	  driver.quit();
  }
  //從Excel檔案獲取測試資料的靜態方法
  public static Object[][] getSearchData(String filePath,String FileName,String sheetName) throws IOException{
		//根據引數傳入的資料檔案路徑和檔名稱,組合出Excel資料檔案的絕對路徑,宣告一個File檔案物件
		File file = new File(filePath + "\\" + FileName);
		//建立FileInputStream物件用於讀取Excel檔案
		FileInputStream inputStream = new FileInputStream(file);
		Workbook Workbook = null;
        //獲取檔名引數的副檔名,判斷是.xlsx檔案還是.xls檔案
		String fileExtensionName = FileName.substring(FileName
				.indexOf("."));
		if (fileExtensionName.equals(".xlsx")) {
			Workbook = new XSSFWorkbook(inputStream);
		} else if (fileExtensionName.equals(".xls")) {
			Workbook = new HSSFWorkbook(inputStream);
		}
		//通過sheetName引數,聲稱Sheet物件
		Sheet Sheet = Workbook.getSheet(sheetName);
		//獲取Excel資料檔案Sheet1中資料的行數,getLastRowNum()方法獲取資料的最後一行行號
		//getFirstRowNum()方法獲取資料的第一行行號,相減之後得出資料的行數,Excel檔案的行號和列號都是從0開始
		int rowCount = Sheet.getLastRowNum() - Sheet.getFirstRowNum();
        //建立list物件儲存從Excel資料檔案讀取的資料
		List<Object[]> records = new ArrayList<Object[]>();
        //迴圈遍歷Excel資料檔案的所有資料,除了第一行,第一行是資料列名稱
		for (int i = 1; i < rowCount + 1; i++) {
            //使用getShow方法獲取行物件
			Row row = Sheet.getRow(i);
			//宣告一個數組,儲存Excel資料檔案每行中的3個數據,陣列的大小用getLastCellNum()方法進行動態宣告,實現測試資料個數和陣列大小一致
			String fields[] = new String[row.getLastCellNum()];
			for (int j = 0; j < row.getLastCellNum(); j++) {
				//使用getCell()和getStringCellValue()方法獲取Excel檔案中的單元格資料
				fields[j] =row.getCell(j).getStringCellValue();
			}
			//將fields的資料物件存入records的list中
			records.add(fields);
		}
		// 將儲存測試資料的List轉換為一個Object的二維陣列
		Object[][] results = new Object[records.size()][];
		// 設定二位陣列每行的值,每行是一個Object物件
		for (int i = 0; i < records.size(); i++) {
			results[i] = records.get(i);
		}
		return results;
  }
}
執行後結果:
PASSED: testSearch("老九門", "演員", "趙麗穎")
PASSED: testSearch("X站警天啟", "導演", "布萊恩·辛格")
PASSED: testSearch("誅仙青雲志", "編劇", "張戩")

===============================================
    Default test
    Tests run: 3, Failures: 0, Skips: 0
===============================================