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

 我来答
宽厚还明净灬赤子4
2016-08-19 · 知道合伙人软件行家
宽厚还明净灬赤子4
知道合伙人软件行家
采纳数:1554 获赞数:7643
国家一等奖学金获得者

向TA提问 私信TA
展开全部
  这是一个测试的话题,同样也是一个开发的话题。现在的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浏览器来作为客户端,所以就不需要下载额外的浏览器执行器。
  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("htt p:/ /ww w.g oog le.c om.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,
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式