Selenium怎樣搭配TestNG:
前3篇我們都是在main方法裏面寫的代碼,
從這一篇開始,我們使用TestNG+Selenium:
首先打開TestNG官網,在地址欄輸入:http://testng.org/doc/
但是,如果你用Maven構建的話,沒有這麼麻煩,不用去官網:
<dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.11</version> </dependency>
用Gradle構建的話就更簡單了:
compile 'org.testng:testng:6.9.6'
好了,TestNG依賴添加完成了,讓我們愉快的開始寫代碼吧!
我們以登錄軟件測試論壇爲例:
就這3步操作;
以下是完整代碼:
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; public class Login51Testing { public static WebDriver driver; @BeforeMethod //測試前的準備工作,我們這裏還沒有封裝 public void beforeMethod() throws InterruptedException { System.setProperty("webdriver.firefox.marionette", "C:\\Program Files\\Mozilla Firefox\\firefox.exe"); String Url = "http://bbs.51testing.com/forum.php"; //軟件測試論壇首頁 driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get(Url); driver.manage().window().maximize(); Thread.sleep(2000); //等待頁面渲染 } @AfterMethod //測試後退出 public void afterMethod() { driver.quit(); } @Test //登錄軟件測試論壇的用例 public void login() throws InterruptedException { driver.findElement(By.xpath(".//*[@id='ls_username']")).sendKeys("abcdef"); //輸入用戶名(隨便寫的) driver.findElement(By.xpath(".//*[@id='ls_password']")).sendKeys("123456"); //輸入密碼(也是隨便寫的) driver.findElement(By.xpath(".//*[@id='lsform']/div/div[1]/table/tbody/tr[2]/td[3]/button")).click(); //點擊登錄 Thread.sleep(2000); Assert.assertTrue(driver.getPageSource().contains("登錄失敗,您還可以嘗試")); //添加斷言:用戶名和密碼都是隨便寫的,那肯定登錄失敗了! } }
現在我們跑一把:
我們發現TestNG全部都是綠色的,說明這個測試用例是成功的: