<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">本章节用一个简单的例子来介绍selenium在web 自动化测中的基本用法。</span>
例:在百度里面搜索‘csdn’,点击‘百度一下’,进入到搜索结果页面。
说明:前期的安装完成, 你可以看到以下jar包:
本人习惯使用chrome浏览器,因此例子也基于chrome编写:
因为selenium-webdriver使用的是各浏览器源生的API, 因此在开始写例子前,我们需要下载chromedriver.exe
下载地址:http://chromedriver.storage.googleapis.com/index.html?path=2.23/
对于windows, chromedriver只有32位:chromedriver_win32.zip,本人亲测对于64位系统,同样可用。
将下载的zip文件,解压到任意目录,里面会有chromedriver.exe。
例子代码:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
public class testBD {
WebElement webElement = null;
WebDriver driver = new ChromeDriver();
@Test(priority = 0) <span style="color:#ff0000;">//添加了testng的声明之后,这个case就是testng case</span>
public void openBD(){
//告诉系统chromedriver.exe的位置
System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe");
driver.get("http://www.baidu.com");
driver.manage().window().maximize();
}
@Test(priority = 10)
public void searchCSDN() throws InterruptedException{
webElement = driver.findElement(By.xpath("//input[@id = \"kw\"]"));
webElement.sendKeys("csdn");
webElement = driver.findElement(By.xpath("//*[@id=\"su\"]"));
webElement.click();
Thread.sleep(3001);
}
@Test(priority = 20)
public void checkSearchResult(){
String pagesorce = driver.getPageSource();
System.out.println("pagesorce:" + pagesorce);
Assert.assertTrue(pagesorce.contains("全球最大中文IT社区,为IT专业技术人员提供最全面的"));
}
}
至此,大家应该搭建起了一个最基本的测试框架。
后续,会从以下几个方面继续优化这个框架
1)数据管理(xpath,期望结果等等);
2)日志管理
3)配置文件管理
4)引入appium, 使框架适用于移动端
5)引入jenkins,管理case的自动执行
.........