最近在转行软件测试,有点艰难,为了提高自己的竞争力,只有不断的学习,学习多一点技术和知识。
这次要学习的是Java+Selenium的Web自动化测试,虽然这个自动化测试技术已经少有人用,或者说已经没人用了,很多相关的插件都不支持更新了,而且所用的到selenium相关jar包的版本必须要和firefox浏览器版本相匹配才能真正跑起来的。
这个需要学习的就不用担心,文末会提供匹配的jar包和Firefox相匹配的版本,下载直接安装即可。
接下来演示如何安装和实现,首先安装firefox浏览器,原本是在附加组件中直接添加就行的,但是这个Firefox的版本好像有点低了,已经不支持添加了,不过没事,在附件中已经下载好了selenium-ide-2.9.0.xpi,将之直接拖到firefox浏览器中,就会出现这样的页面:(点击立即安装,然后重启即可)
这是selenium IDE就已经安装完毕,简单的来录制一个百度搜索功能,进入百度搜索页面,在工具栏中打开selenium IDE开始录制
在搜索框输入selenium点回车,就录制完毕,点击停止录制。而后进行转换成Java代码:
点击确定,拷贝Source里面的所有代码
打开MyEclipse,新建一个Java项目,接着将selenium-2.46.0文件夹中的所有jar包导进项目中:
最后将复制的代码全部拷贝进去,记得修改包名、类名和添加firefox的安装路径:
package com.itman.seleniumtest;
import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class SeleniumTest {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
@Before
public void setUp() throws Exception {
// 这里要修改你的Firefox的安装路径
System.setProperty("webdriver.firefox.bin", "D:\\Firefox\\firefox.exe");
driver = new FirefoxDriver();
baseUrl = "https://www.baidu.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testUntitled() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.id("kw")).click();
driver.findElement(By.id("kw")).clear();
driver.findElement(By.id("kw")).sendKeys("selenium");
driver.findElement(By.id("su")).click();
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
最后就是运行啦,右键->Run As->Junit Test:
接着会看到Firefox浏览器自动打开,进入百度搜索页面,然后自动输入selenium进行搜索,最后关闭。MyEclipse最终就测试通过:
一个简单的Java+Selenium自动化测试百度搜索功能就这样实现了。
资源文件下载