網站自動化測試Selenium的 Hello World

網站自動化測試Selenium的 Hello World

Selenium HelloWorld

這篇文章主要用一個範例程式說明 Selenium的基本運作。

這個範例程式會自動啟動 FireFox,瀏覽 Google網站,

模擬使用者輸入 “Hello World”的搜尋關鍵字,接著就讓 google 開始搜尋。

Selenium的Hello World與其他程式不同,主要是因為Selenium必須與 Browser 溝通互動。

因此 Selenium 模擬輸入的 “Hello World”必須確認是否 Browser 有收到並且正確的在該瀏覽器上執行。

測試情境

這個 Selenium 測試程式,主要會自動進行下列動作

1. 啟動 Firefox

2. 瀏覽至 www.google.com並且將視窗最大化

3. 輸入 Hello World並執行

 

實務經驗

這個程式範例為了容易了解操作 Selenium相關的 API,所以這樣的範例比較直覺了解。

但是實務上的測試自動化通常程式”架構”不是這樣的.

為什麼呢? 哪裡不一樣?

因為自動化測試的目的是要驗證(assertion)測試結果,並且有許多的測試個案(testing cases)。

所以,實務上進行自動化測試通常會利用 Java Junit 或是 python unittest 的這種 unit testing 的模組來完成。

透過使用 unit testing 的模組可以更容易的做到

  • 測試個案的管理
  • 每個測試個案的執行結果,格式化與報表輸出
  • 驗證(assertion)測試結果

 

程式範例

[pastacode lang=”java” message=”Selenium Hello World” highlight=”” provider=”manual”]

package mySelenium;

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.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Selenium2Example  {
    public static void main(String[] args) throws InterruptedException {

    	// Create a new instance of the Firefox driver

        WebDriver driver = new FirefoxDriver();
        //By default, it will wait for 10 sec
        driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

        // Launch the FireFox browser and Visit Google page
        driver.get("http://www.google.com");
        //  Max the window
        driver.manage().window().maximize();

        // Locate the search input field by name = "q"
        WebElement element = driver.findElement(By.name("q"));

        // Text Input "Selenium" 
        element.sendKeys("Hello World");
                
        
        // simulate the click search button
        element.submit();

        // Check the title of the page
        System.out.println("Page title is: " + driver.getTitle());
        
        
        //Close the browser
        //sleep for 3 sec before close the browser
        Thread.sleep(3000);
        driver.quit();
    }
}

[/pastacode]

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *