1.下载必要的依赖文件selenium-server-standalone-2.25.0.jar、junit-4.7.jar并将其放在项目的lib文件夹中(我这里使用的是Firefox浏览器作为客户端,所以有无需下载额外的浏览器执行器,如果您想使用IE或Chrome作为客户端,请下载相应的执行器
【2.创建测试项目,在文件中创建测试并添加。 以下代码:
importcom.thoughtworks.selenium.Selenium;
importjunit.framework.TestCase;
importorg.junit.
importorg.junit.Before;
importorg.junit.Test;
importorg.junit.runner.RunWith;
importorg.junit运行程序。 BlockJUnit4ClassRunner;
导入org.openqa.selenium.By;
导入org.openqa.selenium.WebDriver;
导入org.openqa.selenium.WebDriverBackedSelenium;;
导入org.openqa.selenium.support.ui.Wait;
导入org.openqa.selenium.support.ui.WebDriverWait;
importjava.io.IOException;
importstaticorg.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
@RunWith(BlockJUnit4ClassRunner.class)
publicclasspickTestextendsTestCase{
protectedstaticSeleniumselenium;
privatestaticWebDriverdriver;
@Before
publicvoidcreateAndStartService()throwsIOException{
selenium=newWebDriverBackedSelenium(newFirefoxDriver(),"");
driver=((WrapsDriver)selenium).getWrappedDriver();
@After
publicvoidcreateAndStopService(){
飞行员。 quit();
<}
<
<@Test
<驱动程序。
get("http://www.google.com.hk"); SearchBox.sendKeys("selenium"); WebElementsearchButton=driver.findElement(By.xpath("//*[@id=\"tsf\"]/div[2]/div[3]/center/input[1]")); searchButton.click(); wait.until(visibilityOfElementLocated(By.xpath("//*[@id=\"ab_name\"]/span"))); } }
这样就进行了一个简单的自动化页面测试。 有些朋友可能不明白这段代码的含义。 在上面的代码中,我将部分标记为红色和蓝色。 让我简单解释一下。 Selenium通过包装浏览器来处理页面,因此我们首先创建一个链接到浏览器的WebDriver对象。 接下来,我们需要使用findeElement和XPath方法查找页面元素,以获取页面对象(代码的红色部分)。 因此,通常我们的一个点击操作会从服务器生成响应,这需要一段时间。 蓝色部分的代码是创建一个pending对象。 您可以使用XPath来确定返回后加载哪个页面元素。 该页面被视为已加载。 同时,等待的对象也有超时的情况。 参数,以便服务器永远不会返回错误。 我们仍然可以完成测试。 如何更快的确定页面元素的XPath,如下:
上一篇:selenium自动化测试框架
下一篇:selenium自动化测试实战