Junits 处理的是unit level 的测试;Selenium 处理的是 functional leve 的测试。虽然它们是完全不同,但仍然可以用Junit 来写 Selenium 测试。
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
public static void openBrowser()
{
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
@BeforeClass,告诉Junit 下面的代码要在所有的test 开始跑之前提前运行。通过这个openBrowser ,相当于打开了一个浏览器。
这只是一个login 功能。相对特殊的是一个 try catch 块和一个assert 判断。只有失败的时候,assert 语句才会起作用。
关于@AfterClass 注解
该注解时告诉Junit 注解,在所有test都跑完后,执行这个方法。这里是关闭浏览器驱动。
参考了:http://www.toolsqa.com/java/junit-framework/junit-test-selenium-webdriver/
Junit Test With Selenium Driver
原文:http://my.oschina.net/pingjiangyetan/blog/424045