selenium webdriver testng自動化測試數據驅動
selenium webdriver testng自動化測試數據驅動
一、數據驅動測試概念
數據驅動測試是相同的測試腳本使用不同的測試數據執行,測試數據和測試行為完全分離。
二、實施數據驅動測試的步驟:
1、編寫測試腳本,腳本需要支持程序對象、文件或者數據庫讀入測試數據。
2、將測試腳本使用的測試數據存入程序對象、文件或者數據庫等外部介質中。
3、運行腳本,循環調用存儲在外部介質的測試數據。
4、驗證所有的測試結果是否符合期望的結果。
三、使用TestNG進行數據驅動
使用@DataProvider注解定義當前方法中的返回對象作為測試腳本的測試數據集。
用法參考代碼:
import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; //搜索2個關鍵詞,驗證搜索結果頁面是否包含期望的關鍵詞 public class DataProviderDemo { private static WebDriver driver; @DataProvider(name="searchData") public static Object[][] data() { return new Object[][] {{"老九門","演員","趙麗穎"},{"X站警天啟","導演","布萊恩·辛格"},{"誅仙青雲志","編劇","張戩"}}; } @Test(dataProvider="searchData") public void testSearch(String searchdata1,String searchdata2,String searchResult) { //打開sogou首頁 driver.get("http://www.sogou.com/"); //輸入搜索條件 driver.findElement(By.id("query")).sendKeys(searchdata1+" "+searchdata2); //單擊搜索按鈕 driver.findElement(By.id("stb")).click(); //單擊搜索按鈕后,等待3秒顯示搜索結果 try{ Thread.sleep(3000); }catch(InterruptedException e){ e.printStackTrace(); } //判斷搜索的結果是否包含期望的關鍵字 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(); } }
運行結果:
PASSED: testSearch("老九門", "演員", "趙麗穎") PASSED: testSearch("X站警天啟", "導演", "布萊恩·辛格") PASSED: testSearch("誅仙青雲志", "編劇", "張戩") =============================================== Default test Tests run: 3, Failures: 0, Skips: 0 ===============================================
上述代碼表示測試方法中3個參數分別使用searchData測試數據集中每個一維數組中的數據進行賦值。
此方法會被調用3次,分別使用測試數據集中的三組數據。