Selenium 關鍵字驅動
//關鍵字方法
package com.keyword;
import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class KeyWordExample {
static WebDriver driver;
WebDriverWait wait;
public void open_Browser(String browserName) {
try {
if (browserName.equalsIgnoreCase("Firefox")) {
File file = new File("D:\\學習資料\\自動化測試\\selenium\\driver\\geckodriver.exe");
System.setProperty("webdriver.gecko.driver", file.getAbsolutePath());
driver = new FirefoxDriver();
wait = new WebDriverWait(driver, 10);
} else if (browserName.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver", "D:/Jars/chromedriver.exe");
driver = new ChromeDriver();
wait = new WebDriverWait(driver, 10);
} else if (browserName.equalsIgnoreCase("IE")) {
System.setProperty("webdriver.ie.driver", "D:/Jars/IEDriverServer.exe");
driver = new InternetExplorerDriver();
wait = new WebDriverWait(driver, 10);
}
} catch (WebDriverException e) {
System.out.println(e.getMessage());
}
}
public void enter_URL(String URL) {
driver.navigate().to(URL);
}
public By locatorValue(String locatorTpye, String value) {
By by = null;
switch (locatorTpye) {
case "id":
System.out.println("=================使用id定位======================");
by = By.id(value);
//wait.until(ExpectedConditions.presenceOfElementLocated(by));
break;
case "name":
System.out.println("=================使用Name定位======================");
by = By.name(value);
// wait.until(ExpectedConditions.presenceOfElementLocated(by));
break;
case "className":
System.out.println("=================使用className定位======================");
by = By.className(value);
//wait.until(ExpectedConditions.presenceOfElementLocated(by));
//
break;
case "xpath":
System.out.println("=================使用xpath定位======================");
by = By.xpath(value);
//wait.until(ExpectedConditions.presenceOfElementLocated(by));
break;
case "css":
System.out.println("=================使用css定位======================");
by = By.cssSelector(value);
//wait.until(ExpectedConditions.presenceOfElementLocated(by));
break;
case "linkText":
System.out.println("=================使用linkText定位======================");
by = By.linkText(value);
//wait.until(ExpectedConditions.presenceOfElementLocated(by));
break;
case "partialLinkText":
System.out.println("=================使用partialLinkText定位======================");
by = By.partialLinkText(value);
//wait.until(ExpectedConditions.presenceOfElementLocated(by));
break;
}
return by;
}
public void enter_Text(String locatorType, String value, String text) {
try {
By locator;
locator = locatorValue(locatorType, value);
WebElement element = driver.findElement(locator);
element.sendKeys(text);
} catch (NoSuchElementException e) {
System.err.format("No Element Found to enter text" + e);
}
}
public void sleep(String seconds) {
try {
Thread.sleep(Integer.parseInt(seconds) * 1000);
System.out.println("休眠" + seconds + "秒");
} catch (InterruptedException e) {
// TODO 自動生成的 catch 塊
e.printStackTrace();
}
}
public void click_On_Link(String locatorType, String value) {
try {
By locator;
locator = locatorValue(locatorType, value);
WebElement element = driver.findElement(locator);
element.click();
} catch (NoSuchElementException e) {
System.err.format("No Element Found to enter text" + e);
}
}
public void click_On_Button(String locatorType, String value) {
try {
By locator;
locator = locatorValue(locatorType, value);
WebElement element = driver.findElement(locator);
element.click();
} catch (NoSuchElementException e) {
System.err.format("No Element Found to perform click" + e);
}
}
public void close_Browser() {
driver.quit();
}
}
//jxl版,Excel工具類
package com.keyword;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import jxl.Sheet;
import jxl.Workbook;
//import jxl.Sheet;
//import jxl.Workbook;
//import jxl.read.biff.BiffException;
import jxl.read.biff.BiffException;
public class ReadExcel {
Workbook wbWorkbook;
Sheet shSheet;
public void openSheet(String filePath) {
FileInputStream fs;
try {
fs = new FileInputStream(filePath);
wbWorkbook = Workbook.getWorkbook(fs);
shSheet = wbWorkbook.getSheet(0);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String getValueFromCell(int iColNumber, int iRowNumber) {
return shSheet.getCell(iColNumber, iRowNumber).getContents();
}
public int getRowCount() {
return shSheet.getRows();
}
public int getColumnCount() {
return shSheet.getColumns();
}
}
Apache poi版
package com.keyword;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
//import jxl.Sheet;
//import jxl.read.biff.BiffException;
public class ExcelUtil {
// private static String fileOutPutFordler;
//
// public static String getFileFordler() {
// return fileOutPutFordler;
// }
//
// public static void setFileFordler(String fileFordler) {
// fileOutPutFordler = fileFordler;
// }
Workbook wb;
Sheet shSheet;
// 讀取excel
/**
*
* @param filePath
* 讀取檔案的路徑
* @return
*/
@SuppressWarnings("resource")
public void readExcel(String filePath, String sheetName) {
// Workbook wb = null;
// if (filePath == null) {
// return null;
// }
String extString = filePath.substring(filePath.lastIndexOf("."));
InputStream is = null;
try {
is = new FileInputStream(filePath);
if (".xls".equals(extString)) {
wb = new HSSFWorkbook(is);
shSheet = wb.getSheet(sheetName);
} else if (".xlsx".equals(extString)) {
wb = new XSSFWorkbook(is);
shSheet = wb.getSheet(sheetName);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 建立Excel檔案
*
* @return Excel物件
* @throws IOException
*/
public static ExcelUtil createExcel(String fileName) {
Workbook wb = null;
if (fileName.endsWith(".xls")) {
wb = new HSSFWorkbook();
wb.createSheet();
}
if (fileName.endsWith(".xlsx")) {
wb = new XSSFWorkbook();
wb.createSheet();
}
try {
OutputStream fileOut = new FileOutputStream(fileName);
wb.write(fileOut);
} catch (FileNotFoundException e) {
// TODO 自動生成的 catch 塊
e.printStackTrace();
} catch (IOException e) {
// TODO 自動生成的 catch 塊
e.printStackTrace();
}
return new ExcelUtil();
}
/***
* 開啟檔案、資料夾
*
* @param folder
* : directory
*/
public static void open_directory(String folder) {
File file = new File(folder);
if (!file.exists()) {
return;
}
Runtime runtime = null;
try {
runtime = Runtime.getRuntime();
runtime.exec("cmd /c start explorer " + folder);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (null != runtime) {
runtime.runFinalization();
}
}
}
/**
* 開啟Excel檔案
*
* @param filePath
*/
public void openSheet(String filePath) {
String extString = filePath.substring(filePath.lastIndexOf("."));
InputStream is = null;
try {
is = new FileInputStream(filePath);
if (".xls".equals(extString)) {
wb = new HSSFWorkbook(is);
shSheet = wb.getSheetAt(0);
} else if (".xlsx".equals(extString)) {
wb = new XSSFWorkbook(is);
shSheet = wb.getSheetAt(0);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
* @param iColNumber
* 列
* @param iRowNumber
* 行
* @return 單元格的值
*/
public String getValueFromCell(int iColNumber, int iRowNumber) {
Row currentRow = shSheet.getRow(iRowNumber);
Cell cell = currentRow.getCell(iColNumber);// 獲取案例路徑
Object cellValue = null;
if (cell != null) {
// 判斷cell型別
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC: {
cellValue = String.valueOf((long) cell.getNumericCellValue());
break;
}
case Cell.CELL_TYPE_FORMULA: {
// 判斷cell是否為日期格式
if (DateUtil.isCellDateFormatted(cell)) {
// 轉換為日期格式YYYY-mm-dd
cellValue = cell.getDateCellValue();
} else {
// 數字
cellValue = String.valueOf((long) cell.getNumericCellValue());
}
break;
}
case Cell.CELL_TYPE_STRING: {
cellValue = cell.getRichStringCellValue().getString();
break;
}
default:
cellValue = "";
}
} else {
cellValue = "";
}
return (String) cellValue;
}
/**
* 獲取最大行數
*
* @return
*/
public int getRowCount() {
return shSheet.getLastRowNum();
}
/**
* 獲取最大列數
*
* @return
*/
public int getColumnCount() {
Row currentRow = shSheet.getRow(0);
return currentRow.getPhysicalNumberOfCells();
}
}
//通過java反射來建立關鍵字和Excel中資料的對映關係
package com.keyword;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.hamcrest.core.IsInstanceOf;
public class KeyWordExecution {
public void runReflectionMethod(String strClassName, String strMethodName, Object... inputArgs) {
Class<?> params[] = new Class[inputArgs.length];
for (int i = 0; i < inputArgs.length; i++) {
if (inputArgs[i] instanceof String) {
params[i] = String.class;
System.out.println("----------------" + params[i]);
}
}
try {
Class<?> cls = Class.forName(strClassName);
Object _instance = cls.newInstance();
Method myMethod = cls.getDeclaredMethod(strMethodName, params);
System.out.println("======================" + myMethod.getName());
myMethod.invoke(_instance, inputArgs);
} catch (ClassNotFoundException e) {
System.err.format(strClassName + ":- Class not found%n");
} catch (IllegalArgumentException e) {
System.err.format("Method invoked with wrong number of arguments%n");
} catch (NoSuchMethodException e) {
System.err.format("In Class " + strClassName + "::" + strMethodName + ":- method does not exists%n");
} catch (InvocationTargetException e) {
System.err.format("Exception thrown by an invoked method%n");
} catch (IllegalAccessException e) {
System.err.format("Can not access a member of class with modifiers private%n");
e.printStackTrace();
} catch (InstantiationException e) {
System.err.format("Object cannot be instantiated for the specified class using the newInstance method%n");
}
}
public static void main(String[] args) {
KeyWordExecution exeKey = new KeyWordExecution();
ReadExcel excelSheet = new ReadExcel();
//ExcelUtil excelSheet=new ExcelUtil();
excelSheet.openSheet("Keywords.xls");
for (int row = 1; row < excelSheet.getRowCount(); row++) {
List<Object> myParamList = new ArrayList<Object>();
String methodName = excelSheet.getValueFromCell(0, row);
for (int col = 1; col < excelSheet.getColumnCount(); col++) {
if (!excelSheet.getValueFromCell(col, row).isEmpty()
& !excelSheet.getValueFromCell(col, row).equals("null")) {
myParamList.add(excelSheet.getValueFromCell(col, row));
}
}
Object[] paramListObject = new String[myParamList.size()];
paramListObject = myParamList.toArray(paramListObject);
exeKey.runReflectionMethod("com.keyword.KeyWordExample", methodName, paramListObject);
}
}
}
關鍵字Excel表
TestCase |
Locator Type |
Locator Value |
Test Data |
open_Browser |
Firefox |
||
enter_Text |
id |
kw |
uiautomator |
sleep |
1 |
||
click_On_Button |
id |
su |
|
sleep |
1 |
||
click_On_Link |
xpath |
/html/body/div[1]/div[5]/div[1]/div[3]/div[3]/h3/a/em |
|
close_Browser |
Maven POM檔案
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test.selenium</groupId>
<artifactId>SeleniumPractice</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SeleniumPractice</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.14.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-firefox-driver -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-firefox-driver</artifactId>
<version>3.14.0</version>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>4.2.1</version>
</dependency>
<dependency>
<groupId>net.sourceforge.tess4j</groupId>
<artifactId>tess4j</artifactId>
<version>4.1.1</version>
<exclusions>
<exclusion>
<groupId>com.sun.jna</groupId>
<artifactId>jna</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-testng -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-testng</artifactId>
<version>1.2.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-java -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.masterthought/cucumber-reporting -->
<dependency>
<groupId>net.masterthought</groupId>
<artifactId>cucumber-reporting</artifactId>
<version>4.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl -->
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version