這是一個測試的話題,同樣也是一個開發的話題。現在的web應用免不了需要進行自動化的頁面測試,那么selenium是一個不錯的選擇。selenium是一個自動化測試框架,它擁有IDE和API接口,可以應用於Java, C#. Python, Ruby等語言。用selenium來構建一個自動化的測試程序非常的簡單。不過首先你需要熟悉web應用里面的request, response概念,以及XPath的用法。這里我將介紹一下如何利用Junit與selenium來實現自動化頁面測試。
1. 下載必要依賴文件selenium-server-standalone-2.25.0.jar, junit-4.7.jar,並將它們放置到工程的lib文件夾下面 (我這里使用Firefox瀏覽器來作為客戶端,所以就不需要下載額外的瀏覽器執行器,如果你想用IE或是Chrome做客戶端,請下載對應的執行器
http://code.google.com/p/selenium/downloads/list)
2. 建立一個測試工程,在工程里創建一個測試文件,並添加如下代碼:
import com.thoughtworks.selenium.Selenium; import junit.framework.TestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.BlockJUnit4ClassRunner; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverBackedSelenium; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.internal.WrapsDriver; import org.openqa.selenium.support.ui.Wait; import org.openqa.selenium.support.ui.WebDriverWait; import java.io.IOException; import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated; @RunWith(BlockJUnit4ClassRunner.class) public class pickTest extends TestCase { protected static Selenium selenium; private static WebDriver driver; @Before public void createAndStartService() throws IOException { selenium = new WebDriverBackedSelenium(new FirefoxDriver(), ""); driver = ((WrapsDriver) selenium).getWrappedDriver(); } @After public void createAndStopService() { driver.quit(); } @Test public void should_open_google_page() throws InterruptedException { driver.get("http://www.google.com.hk"); WebElement searchBox = driver.findElement(By.xpath("//*[@id=\"lst-ib\"]")); searchBox.sendKeys("selenium"); WebElement searchButton = driver.findElement(By.xpath("//*[@id=\"tsf\"]/div[2]/div[3]/center/input[1]")); searchButton.click(); Wait<WebDriver> wait = new WebDriverWait(driver, 30); wait.until(visibilityOfElementLocated(By.xpath("//*[@id=\"ab_name\"]/span"))); } }
3. 運行這個測試,你將看到firebox瀏覽器被自動啟動,然后會自動的輸入selenum並搜索。
這樣,一個簡單的自動化頁面測試就完成了。有的朋友可能不太明白這段代碼的含義。上面的代碼中我標出了紅色和藍色兩部分,我簡單解釋一下。Selenium是通過對瀏覽器的包裝來進行頁面處理的,因此我們首先會創建一個與瀏覽器相關的WebDriver對象。然后我們需要查找頁面元素就是通過findeElement的方法和XPath的方式來獲取頁面對象(紅色部分代碼)。那么通常我們的一個點擊操作產生服務器相應,這里就需要一些時間。藍色部分的代碼就是創建一個等待對象,你可以通過XPath的方式來確定返回后頁面上的哪個元素加載完了就認為頁面加載完了,同時等待對象也有一個超時設置,這樣即是服務器端一直不返回或出錯。我們依然可以結束測試。如何更快的確定頁面元素的XPath,如下: