版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29956725/article/details/88026557
1. java 项目开发的话,直接用Maven比较方便,已经集成了各个浏览器
导入Maven依赖
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
2. 导入maven jar包之后,查看下载的maven jar
通过jar包可以查看出,通过maven的话,已经支持chrome,firefox,ie,opera,safari等主流浏览器了
3. 我们可以通过给火狐或者谷歌浏览器安装插件来录制操作,从而生成一段test case,以下是火狐安装,火狐版本
不能选择太新,具体看查看Selenium官网
具体的java代码如下:
package cn.ok.http.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class SeleniumUtils {
public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
executeWithAnnotationMehtod();
}
static void executeWithAnnotationMehtod() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
// 通过反射执行测试类中的有@Test修饰的方法
Class<?> c = SeleniumUtils.class;
Object test = c.newInstance();
Method[] ms = c.getDeclaredMethods();
for (Method m : ms) {
// System.out.println(m);
// 判定方法上有没有Test注解
if (m.isAnnotationPresent(MockTest.class)) {
try{
m.invoke(test);
}
catch(Exception e){
e.printStackTrace(System.out); //这样则可以顺序输出
}
}
}
}
/**
* 用火狐进行测试,打开百度
*/
// @MockTest
void startWithFireFox(){
// 这里要修改你的Firefox的安装路径
System.setProperty("webdriver.firefox.bin", "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); //设置默认超时时间
driver.get("https://www.baidu.com");
// 获取 网页的 title
System.out.println("The testing page title is: " + driver.getTitle());
// driver.findElement(By.id("search-input")).sendKeys("selenium");
driver.findElement(By.id("kw")).sendKeys("selenium");
driver.findElement(By.id("su")).click();
// driver.quit();
}
/**
* 用谷歌进行测试打开百度,搜索Selenium , kw为文本关键字文本框按钮,su为提交按钮
*/
// @MockTest
void startWithChorme(){
// 这里要修改你的谷歌的安装路径
System.setProperty("webdriver.chrome.driver", "D:\\idea\\workspace\\okHttp\\src\\main\\Driver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
// driver.manage().timeouts().implicitlyWait(300, TimeUnit.SECONDS); //设置默认超时时间
driver.get("https://www.baidu.com");
// 获取 网页的 title
System.out.println("The testing page title is: " + driver.getTitle());
driver.findElement(By.id("kw")).sendKeys("selenium");
driver.findElement(By.id("su")).click();
driver.quit();
}
@MockTest(desc = "文件上传")
public void testUntitled() throws Exception {
File file = new File("");
String filePath = file.getAbsolutePath() + File.separator + "src.main.java".replace(".", File.separator) + File.separator + this.getClass().getName().replace(".", File.separator);
String uploadFileName = filePath + ".java";
String targetFile = filePath + ".html";
file = new File(targetFile);
String html = "<!DOCTYPE html>\n" +
"<html>\n" +
"<head>\n" +
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n" +
"<title>测试</title>\n" +
"</head>\n" +
"<body>\n" +
" <h1>上传</h1>\n" +
" <form method=\"post\" action=\"/TomcatTest/UploadServlet\"\n" +
" enctype=\"multipart/form-data\">\n" +
" 文件路径: <input type=\"file\" name=\"uploadFile\" /> <br />\n" +
" <br /> <input type=\"submit\" value=\"上传\" />\n" +
" </form>\n" +
"</body>\n" +
"</html>";
if (file.exists()) {
file.delete();
}
file.createNewFile();
FileOutputStream out = new FileOutputStream(targetFile);
out.write(html.getBytes("utf-8"));
out.flush();
out.close();
System.setProperty("webdriver.chrome.driver", "D:\\idea\\workspace\\okHttp\\src\\main\\Driver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get(targetFile);
JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
driver.findElement(By.name("uploadFile")).sendKeys(uploadFileName);
// 获取文件上传文半框位置,传入文件上传地址。
Thread.sleep(1000);
JavascriptExecutor js=(JavascriptExecutor) driver;
//3秒后执行
js.executeAsyncScript("setTimeout(\"alert('2秒后准备关闭')\",2000)");
Thread.sleep(2000);
// driver.close();
// driver.quit();
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.TYPE })
@interface MockTest {
String desc() default "";
}
如果是标准录制生成的话,则如下代码:
package utils;
import java.awt.*;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
public class DevAclWebTest {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
@Before
public void setUp() throws Exception {
System.setProperty("webdriver.firefox.bin", "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
driver = new FirefoxDriver();
baseUrl = "http://10.64.94.36:8081/";
// driver.manage().timeouts().pageLoadTimeout(-1, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(1000, TimeUnit.SECONDS);
}
// http://10.64.94.36:8081/auth.do?UTM_source=0TIP&UTM_content=666&tipperToken=xqoXVXgKKsUc65RGBnIy-p9EhTGcpXpGHvyoa1lutI5sby4pobSP6KeQgzgHaJIf
@Test
public void testTSSS() throws Exception {
//test1
driver.get(baseUrl + "login.do?r=-417444300&tipperToken=xqoXVXgKKsUc65RGBnIy-p9EhTGcpXpGHvyoa1lutI5sby4pobSP6KeQgzgHaJIf&sourceReferrer=&UTM_group=&UTM_medium=&UTM_term=&UTM_campaign=&UTM_content=700&UTM_source=0TIP#s");
driver.findElement(By.id("identity")).clear();
driver.findElement(By.id("identity")).sendKeys("8341414");
driver.findElement(By.id("phoneNumber")).clear();
driver.findElement(By.id("phoneNumber")).sendKeys("19685678963");
driver.findElement(By.id("continueBtn")).click(); //登陆
//test2
driver.findElement(By.id("product-selection-continue")).click(); //选择产品提交
//test3
WebElement idCardFrontElement = driver.findElement(By.id("idCardFront"));
Actions act = new Actions(driver);
act.click(idCardFrontElement).perform();
act.sendKeys(driver.findElement(By.id("idCardFrontInput")),"D:\\test\\zheng.jpg").perform();
driver.findElement(By.id("name")).sendKeys("汤兴发");
}
@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;
}
}
}
其中火狐和谷歌Driver驱动如下: