如何利用selenium来进行自动化页面测试

这是一个测试的话题,同样也是一个开发的话题。现在的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做客户端,请下载对应的执行器

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"))); } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzzsxp.html