Junit Test With Selenium Driver

Junits 和 Selenium

    Junits 處理的是unit level 的測試;Selenium 處理的是 functional leve 的測試。雖然它們是徹底不一樣,但仍然能夠用Junit 來寫 Selenium 測試。java

一個完整的例子

import java.util.concurrent.TimeUnit;
 
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
 
public class SeleniumTest {
    private static FirefoxDriver driver;
    WebElement element;
 
    @BeforeClass
    public static void openBrowser(){
        driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    } 
 
    @Test
    public void valid_UserCredential(){
        System.out.println("Starting test " + new Object(){}.getClass().getEnclosingMethod().getName());
        driver.get("http://www.store.demoqa.com");	
        driver.findElement(By.xpath(".//*[@id='account']/a")).click();
        driver.findElement(By.id("log")).sendKeys("testuser_3");
        driver.findElement(By.id("pwd")).sendKeys("Test@123");
        driver.findElement(By.id("login")).click();
        try{
            element = driver.findElement (By.xpath(".//*[@id='account_logout']/a"));
        }catch (Exception e){
        }
        
        Assert.assertNotNull(element);
        System.out.println("Ending test " + new Object(){}.getClass().getEnclosingMethod().getName());
    }
 
    @Test
    public void inValid_UserCredential()
    {
        System.out.println("Starting test " + new Object(){}.getClass().getEnclosingMethod().getName());
        driver.get("http://www.store.demoqa.com");	
	driver.findElement(By.xpath(".//*[@id='account']/a")).click();
	driver.findElement(By.id("log")).sendKeys("testuser");
	driver.findElement(By.id("pwd")).sendKeys("Test@123");
	driver.findElement(By.id("login")).click();
	try{
	    element = driver.findElement (By.xpath(".//*[@id='account_logout']/a"));
	}catch (Exception e){
	}
        Assert.assertNotNull(element);
        System.out.println("Ending test " + new Object(){}.getClass().getEnclosingMethod().getName());
    }
 
    @AfterClass
    public static void closeBrowser(){
        driver.quit();
    }
}

關於BeforeClass 註解

    @BeforeClass
    public static void openBrowser()
    {
        driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }

    @BeforeClass,告訴Junit 下面的代碼要在全部的test 開始跑以前提早運行。經過這個openBrowser ,至關於打開了一個瀏覽器。
web

關於inValid_UserCredential 方法

   這只是一個login 功能。相對特殊的是一個 try catch 塊和一個assert 判斷。只有失敗的時候,assert 語句纔會起做用。
瀏覽器

關於@AfterClass 註解測試

    該註解時告訴Junit 註解,在全部test都跑完後,執行這個方法。這裏是關閉瀏覽器驅動。
ui

待繼續補充......

參考了:http://www.toolsqa.com/java/junit-framework/junit-test-selenium-webdriver/ spa

相關文章
相關標籤/搜索