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

Python011

如何利用selenium来进行自动化页面测试,第1张

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做客户端,请下载对应的执行器

http://code.google.com/p/selenium/downloads/list)

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

      <span style="color: #ff0000">WebElement searchBox = driver.findElement(By.xpath("//*[@id=\"lst-ib\"]"))</span>

      searchBox.sendKeys("selenium")

      WebElement searchButton = driver.findElement(By.xpath("//*[@id=\"tsf\"]/div[2]/div[3]/center/input[1]"))

      searchButton.click()

      <span style="color: #3366ff">Wait<WebDriver>wait = new WebDriverWait(driver, 30)

      wait.until(visibilityOfElementLocated(By.xpath("//*[@id=\"ab_name\"]/span")))</span>

  }

}

3. 运行这个测试,你将看到firebox浏览器被自动启动,然后会自动的输入selenum并搜索。

这样,一个简单的自动化页面测试就完成了。有的朋友可能不太明白这段代码的含义。上面的代码中我标出了红色和蓝色两部分,我简单解释一下。Selenium是通过对浏览器的包装来进行页面处理的,因此我们首先会创建一个与浏览器相关的WebDriver对象。然后我们需要查找页面元素就是通过findeElement的方法和XPath的方式来获取页面对象(红色部分代码)。那么通常我们的一个点击操作产生服务器相应,这里就需要一些时间。蓝色部分的代码就是创建一个等待对象,你可以通过XPath的方式来确定返回后页面上的哪个元素加载完了就认为页面加载完了,同时等待对象也有一个超时设置,这样即是服务器端一直不返回或出错。我们依然可以结束测试。如何更快的确定页面元素的XPath,如下:

在我们打开Sketchup界面时,首先会选择模版,或者是默认的模版,这个模版规定了我们的尺寸单位,我们画的线是按照选择的单位格式来进行计算和规划。

在二次开发中,默认的单位为英寸,有时候需要对绘制的线,进行长度统计和单位转换,可通过调用方法进行英寸单位的互转。

运行结果:

字符串:

数组: