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 public static void openBrowser() { driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); }
@BeforeClass,告诉Junit 下面的代码要在全部的test 开始跑以前提早运行。经过这个openBrowser ,至关于打开了一个浏览器。
web
这只是一个login 功能。相对特殊的是一个 try catch 块和一个assert 判断。只有失败的时候,assert 语句才会起做用。
浏览器
关于@AfterClass 注解测试
该注解时告诉Junit 注解,在全部test都跑完后,执行这个方法。这里是关闭浏览器驱动。
ui
参考了:http://www.toolsqa.com/java/junit-framework/junit-test-selenium-webdriver/ spa