Java+Selenium+TestNG关键字驱动测试框架

  1. 在Eclipse新建Java project,并配置好工程中的WebDriver、JUnit、TestNG环境,并导入与Excel操作以及Log4j相关的JAR文件到工程中
  2. 在工程中新建四个Packages:
  3. cn.summer.configuration:主要用于实现框架中的各项配置
    KeyWordsAction.java
package cn.outlook.txp.configuration;

import java.util.List;

import org.apache.log4j.xml.DOMConfigurator;
import org.junit.Assert;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;


import cn.outlook.txp.testScripts.TestSuiteByExcel;
import cn.outlook.txp.util.Constant;
import cn.outlook.txp.util.KeyBoardUtil;
import cn.outlook.txp.util.Log;
import cn.outlook.txp.util.ObjectMap;
import cn.outlook.txp.util.WaitUtil;

public class KeyWordsAction {
	//声明静态WebDriver对象,用于在此类中对相关Driver进行操作
	public static WebDriver driver;
	//声明存储定位表达配置文件的ObjectMap对象
	private static ObjectMap objectMap = new ObjectMap(
			Constant.ObjectMap_FilePath);
	static {
		DOMConfigurator.configure("log4j.xml");
	}
	/*此方法的名称对用Excel文件“关键字”列中的open_browser关键字,
	 * Excel文件中的“操作值”列中的内容用于指定用何种测试浏览器运行测试用例。 
	 */
	public static void open_browser(String string, String browserName) {
		if(browserName.contains("ie")) {
			System.setProperty("webdriver.ie.driver", Constant.IEDriverPath);
			
			Log.info("IE浏览器实例已经声明");
			driver = new InternetExplorerDriver();
						
		}else if(browserName.contains("firefox")) {
			//若WebDriver无法打开Firefox浏览器,才需增加此代码设定Firefox浏览器的所在路径
			System.setProperty("webdriver.firefox.bin", "C:\\Program Files\\Mozilla Firefox\\firefox.exe");
			//加载Firefox浏览器的驱动程序
			System.setProperty("webdriver.gecko.driver", Constant.FirefoxDriverPath);
			
			Log.info("Firefox浏览器实例已经声明");
			driver = new FirefoxDriver();
			
		}else if(browserName.contains("chrome")){
			System.setProperty("webdriver.chrome.driver", Constant.ChromeDriverPath);
			
			Log.info("Chrome浏览器实例已经声明");
			driver = new ChromeDriver();	
			
		}else {
			System.setProperty("webdriver.edge.driver", Constant.EdgeDriverPath);
			Log.info("Edge浏览器实例已经声明");
			driver = new EdgeDriver();
		}
	}
	public static void navigate(String string, String url) {
		Log.info("浏览器访问网址:"+url);
		driver.get(url);
		
		Log.info("浏览器窗口最大化");
		driver.manage().window().maximize();
	}
	
	public static void switch_frame(String locatorExpression, String string) {
		try {
			driver.switchTo().frame(driver.findElement(objectMap.getLocator(locatorExpression)));
			Log.info("进入Frame "+locatorExpression+"成功!");
		}catch(Exception e) {
			TestSuiteByExcel.testResult = false;
			Log.info("进入Frame "+locatorExpression+"失败,具体异常信息:"+e.getMessage());
			e.printStackTrace();
		}
	}
	public static void default_frame(String string1, String string2) {
		try {
			driver.switchTo().defaultContent();
			Log.info("退出frame成功!");
		}catch(Exception e) {
			TestSuiteByExcel.testResult = false;
			Log.info("退出frame失败,具体异常信息: "+e.getMessage());
			e.printStackTrace();
		}
	}
	public static void sleep(String string, String sleepTime) {
		try{
			
			Log.info("休眠"+Integer.parseInt(sleepTime)/1000+"秒成功");
			WaitUtil.sleep(Integer.parseInt(sleepTime));
		}catch(Exception e) {
			TestSuiteByExcel.testResult = false;
			Log.info("线程休眠时出现异常,具体异常信息:"+e.getMessage());
			e.printStackTrace();
		}
		
	}
	public static void click_Mail(String locatorExpression, String emailSubject) {
		try {
			
			List<WebElement> elements = driver.findElements(objectMap.getLocator(locatorExpression));			
			Log.info("邮箱里有"+elements.size()+"封TxP的邮件");
			boolean flag = false;					
			for(int i = 0;i<elements.size();i++) {
				WebElement element = elements.get(i);
				//System.out.println(element.getAttribute("aria-label"));				
				if(element.getAttribute("aria-label").contains(emailSubject))
				{					
					Log.info("查看邮件: "+emailSubject);
					flag = true;
					element.click();					
				}							
			}	
			if(flag != true) {	
			    TestSuiteByExcel.testResult = false;												
				Log.info("没有找到邮件: "+emailSubject+"!");
			}
		}catch(Exception e) {
			TestSuiteByExcel.testResult = false;
			Log.info("打开邮件出现异常,具体异常信息:"+e.getMessage());
			e.printStackTrace();
		}
	}
	
	public static void Assert_String(String string, String assertString) {
		try {
			Log.info("成功断言关键字: "+assertString);
			Assert.assertTrue(driver.getPageSource().contains(assertString));
		}catch(AssertionError e) {
			TestSuiteByExcel.testResult = false;
			Log.info("断言页面中是否存在"+assertString+"失败!具体断言失败信息: "+e.getMessage());
			System.out.println("断言失败");
		}
	}
	public static void close_browser(String string1,String string2) {
		try {
			System.out.println("浏览器关闭函数被执行");
			Log.info("关闭浏览器窗口");
			driver.quit();
		}catch(Exception e) {
			TestSuiteByExcel.testResult = false;
			Log.info("关闭浏览器出现异常,具体异常信息:"+e.getMessage());
			e.printStackTrace();
		}
	}
	public static void WaitFor_Element(String locatorExpression, String string) {
		try {
			WaitUtil.waitWebElement(driver, objectMap.getLocator(locatorExpression));
			Log.info("显示等待元素出现,元素是:"+locatorExpression);
		}catch(Exception e) {
			TestSuiteByExcel.testResult = false;
			Log.info("等待元素出现异常,具体异常信息:"+e.getMessage());
			e.printStackTrace();
		}
	}
	public static void input(String locatorExpression, String inputString) {
		try {
			driver.findElement(objectMap.getLocator(locatorExpression)).clear();
			Log.info("清除 "+locatorExpression+" 输入框中的所有内容");
			driver.findElement(objectMap.getLocator(locatorExpression)).sendKeys(inputString);
			Log.info("在 "+locatorExpression+" 输入框中输入: "+inputString);
			
		}catch(Exception e) {
			TestSuiteByExcel.testResult = false;
			Log.info("在"+locatorExpression+"输入框中输入"+inputString+"时出现异常,具体异常信息:"+e.getMessage());
			e.printStackTrace();
		}
	}
	public static void click(String locatorExpression, String inputString) {
		try {
			driver.findElement(objectMap.getLocator(locatorExpression)).click();
			Log.info("单击 "+locatorExpression+" 页面元素成功");						
		}catch(Exception e) {
			TestSuiteByExcel.testResult = false;
			Log.info("单击 "+locatorExpression+" 页面元素失败,具体异常信息:"+e.getMessage());
			e.printStackTrace();
		}
	}
	public static void click_sure(String locatorExpression, String sureclick) {
		try {
			if(sureclick.trim().equals("是")) {
				driver.findElement(objectMap.getLocator(locatorExpression)).click();
				Log.info("单击 "+locatorExpression+"页面元素成功");
			}
		}catch(Exception e) {
			TestSuiteByExcel.testResult = false;
			Log.info("单击"+locatorExpression+" 页面元素失败,具体异常信息:"+e.getMessage());
			e.printStackTrace();
		}
	}
	public static void press_Tab(String string1, String string2) {
		try {
			Thread.sleep(2000);
			KeyBoardUtil.pressTabKey();
			Log.info("按Tab键成功");
		}catch(Exception e) {
			TestSuiteByExcel.testResult = false;
			Log.info("按Tab键时出现异常,具体异常信息: "+e.getMessage());
			e.printStackTrace();
		}
	}
	public static void press_Enter(String string1, String string2) {
		try {			
			KeyBoardUtil.pressTabKey();
			Log.info("按Enter键成功");
		}catch(Exception e) {
			TestSuiteByExcel.testResult = false;
			Log.info("按Enter键时出现异常,具体异常信息: "+e.getMessage());
			e.printStackTrace();
		}
	}
	public static void pasteString(String string, String pasteContent) {
		try {			
			KeyBoardUtil.setAndctrlVClipboardData(pasteContent);
			Log.info("成功粘贴文本: "+pasteContent);
		}catch(Exception e) {
			TestSuiteByExcel.testResult = false;
			Log.info("在输入框粘贴内容时出现异常,具体异常信息: "+e.getMessage());
			e.printStackTrace();
		}
	}		
}

  1. cn.summer.data:用于存储框架所使用的测试数据文件
    ObjectMap.properties,存储页面元素的定位方法,例如:
login.signInLink=xpath>//a[text()='Sign in']
login.username=name>loginfmt
login.nextButton=xpath>//input[@value='Next']
login.password=name>passwd
login.signInButton=xpath>//input[@value='Sign in']

关键字驱动测试用例.xlsx
TestSuite sheet
在这里插入图片描述
测试用例的测试步骤Sheet
在这里插入图片描述
7. cn.summer.testScript:用于实现具有测试逻辑的测试脚本
TestSuiteByExcel.java

package cn.summer.testScripts;

import java.lang.reflect.Method;
import org.junit.BeforeClass;
import org.openqa.selenium.WebDriver;
import org.apache.log4j.xml.DOMConfigurator;
import org.testng.Assert;
import org.testng.annotations.Test;

import cn.summer.configuration.KeyWordsAction;
import cn.summer.util.Constant;
import cn.summer.util.ExcelUtil;
import cn.summer.util.Log;

public class TestSuiteByExcel {
	public static Method method[];
	public static String keyword;
	public static String locatorExpression;
	public static String value;
	public static KeyWordsAction keyWordsaction;
	public static int testStep;
	public static int testLastStep;
	public static String testCaseID;
	public static String testCaseRunFlag;		
	public static String testStepRunFlag;	
	public static boolean testResult;	
	
	@Test
	public void testTestSuite() throws Exception{
		//声明一个关键动作类的实例		
		keyWordsaction = new KeyWordsAction();
		//使用Java的反射机制获取KeyWordsAction类的所有方法对象
		method = keyWordsaction.getClass().getMethods();
		//定义Excel文件的路径
		String excelFilePath = Constant.Excel_FilePath;
		//设定读取Excel文件的"ReadEmail"Sheet为操作目标
		ExcelUtil.setExcelFile(excelFilePath);
		//读取“TestSuite”Sheet中的测试用例总数
		int testCasesCount = ExcelUtil.getRowCount(Constant.Sheet_TestSuite);
		//使用for循环,执行“TestSuite”Sheet中所有标记为“y”的测试用例
		for(int testCaseNo = 1; testCaseNo <= testCasesCount; testCaseNo++) {
			//读取“TestSuite”Sheet中每行的测试用例序号
			testCaseID = ExcelUtil.getCellData(Constant.Sheet_TestSuite, testCaseNo, Constant.Col_TestCaseID);
			//读取“TestSuite”Sheet中每行的“是否运行”列中的值
			testCaseRunFlag = ExcelUtil.getCellData(Constant.Sheet_TestSuite, testCaseNo, Constant.Col_TestCaseRunFlag);
			//如果“是否运行”列中的值为“y”,则执行测试用例的所有步骤
			if(testCaseRunFlag.trim().equals("y")) {
				//在日志中打印测试用例开始执行的信息
				Log.startTestCase(testCaseID);
				//设定测试用例的当前结果为“True”,即表明测试执行成功
				testResult = true;
				//获取当前要执行测试用例的第一个步骤所在行的行号
				testStep = ExcelUtil.getFirstRowContainsTestCaseID(
						testCaseID, testCaseID, Constant.Col_TestCaseID);
				//在对应的测试用例Sheet中,获得当前要执行测试用例的最后一个步骤,所在行的行号
				testLastStep = ExcelUtil.getTestCaseLastStepRow(
			    		testCaseID, testCaseID, testStep);
			    for(; testStep < testLastStep; testStep++) {
			    	
			    	testStepRunFlag = ExcelUtil.getCellData(testCaseID, testStep, Constant.Col_TestStepRunFlag);
			    	if(testStepRunFlag.trim().equals("y")) {			    		
			    		//从测试步骤的Sheet中读取关键字和操作值,并调用executeAction方法执行
			    		keyword = ExcelUtil.getCellData(testCaseID, 
			    			testStep, Constant.Col_KeyWordAction);
			    		//在日志中打印关键字信息
			    		Log.info("从Excel文件读取到的关键字是: "+keyword);			    				    	
			    		locatorExpression = ExcelUtil.getCellData(testCaseID,
			    			testStep, Constant.Col_LocatorExpression);	
			    		//在日志中打印定位表达式信息
			    		Log.info("从Excel文件读取的表达式是: "+locatorExpression);			    				    	
			    		value = ExcelUtil.getCellData(testCaseID, 
			    			testStep, Constant.Col_ActionValue);
			    		//在日志中打印操作值信息
			    		Log.info("从Excel文件读取的操作值是: "+value);			    	
			    		execute_Actions();			    	
			    		if(testResult == false) {
			    			/*如果测试用例的任何一个测试步骤执行失败,则"TestSuite"Sheet中的当前
				    		 * 执行测试用例的执行结果设定为“测试执行失败”
				    		 */
			    			ExcelUtil.setCellData(Constant.Sheet_TestSuite, testCaseNo, 
			    				Constant.Col_TestSuiteTestResult, "测试执行失败");			    		
			    			//在日志中打印测试用例执行完毕的信息
			    			Log.endTestCase(testCaseID);
			    			/*
			    			 * 如果当前测试用例出现执行失败的情况,则将整个测试用例设定为失败状态,
				    		 * 利用break语句跳出当前的for循环,继续执行TestSuite中的下一个测试用例
				    		 */
			    			break;			    	
			    		}			    	
			    		if(testResult==true) {	
			    			/*
				    		 * 如果测试用例的所有步骤执行成功,则将在“TestSuite”Sheet中的当前
				    		 * 执行测试用例的执行结果设定为“测试执行成功”
				    		 */
			    			ExcelUtil.setCellData(Constant.Sheet_TestSuite, 
			    				testCaseNo, Constant.Col_TestSuiteTestResult, "测试执行成功");			    	
			    		}			    
			    	}				
			    					
			    }
			    
			}
		}		
	}
	private static void execute_Actions() {
		try {
			for(int i = 0;i<method.length;i++) {
				//使用反射的方式,找到关键字对应的测试方法,并将value(操作值)作为测试方法的函数值进行调用
				if(method[i].getName().equals(keyword)) {
					method[i].invoke(keyWordsaction,locatorExpression, value);					
					if(testResult == true) {
						/*
						 * 当前测试步骤执行成功,在“ReadMail01”Sheet中,会将当前执行的
						 * 测试步骤结果设定为“测试步骤执行成功”
						 */
						ExcelUtil.setCellData(testCaseID, 
								testStep, Constant.Col_TestStepTestResult, "测试步骤执行成功");
						break;
					}else {
						/*
						 * 当前测试步骤执行失败,在“ReadMail01”Sheet中,会将当前执行的
						 * 测试步骤结果设定为“测试步骤执行失败”
						 */
						ExcelUtil.setCellData(testCaseID, 
								testStep, Constant.Col_TestStepTestResult, "测试步骤执行失败");
						//测试步骤执行失败,则直接关闭浏览器,不再执行后续的测试
						KeyWordsAction.close_browser("","");
						break;
					}					
				}
			}
		}catch(Exception e) {
			//在调用测试方法的过程中,若出现异常,则将测试设定为失败状态,停止执行测试用例
			Log.info("执行出现异常,测试用例执行失败!");
			Assert.fail("执行出现异常,测试用例执行失败!");
		}
	}

	@BeforeClass
	public void BeforeClass() {	
		//设定Log4j的配置文件为“log4j.xml"
		DOMConfigurator.configure("log4j.xml");
	}
}

  1. cn.summer.util:用于实现封装好的常用测试方法
    Constant.java
package cn.summer.util;

public class Constant {
	//工程包、包名、上一级包名
	public static String projectDir;
	public static String packageName;
	public static String packageParentDir;
	
	//获取当前文件所在目录的父目录的绝对路径
	public static String parentDirPath = getParentPath();
	//测试用例及数据相关常量设定
	//Excel文件路径
	public static String Excel_FilePath = parentDirPath+"\\data\\关键字驱动测试用例.xlsx";
	
	//objectMap.properties配置文件所在路径
	public static String ObjectMap_FilePath = parentDirPath+"\\data\\objectMap.properties";
	
	//获取所在目录的父目录的绝对路径方法
	public static String getParentPath() {
		//获取工程路径
		projectDir = System.getProperty("user.dir")+"\\src";
		//获取类所在包名
		packageName = Constant.class.getPackage().getName();
		//获取类所在包的上一级包名
		packageParentDir = packageName.substring(0,packageName.lastIndexOf("."));
		//格式化包名为路径名
		packageParentDir = String.format("/%s/",packageParentDir.contains(".")?
				packageParentDir.replaceAll("\\.","/"):packageParentDir);
		return projectDir+packageParentDir;

	}
	public static final String Sheet_TestSuite = "TestSuite";
	
	public static final int Col_TestCaseID = 0;
	public static final int Col_TestCaseRunFlag = 3;
	public static final int Col_TestSuiteTestResult = 4;
	

	public static final int Col_KeyWordAction = 3;    
    public static final int Col_LocatorExpression = 4;   
    public static final int Col_ActionValue = 5;
	public static final int Col_TestStepRunFlag = 6;
	public static final int Col_TestStepTestResult = 7;
	
				  
    public static final String ChromeDriverPath = "D:\\Developer\\Eclipse\\KeyWordsActionDrivenTest\\Driver\\chromedriver.exe";
    public static final String FirefoxDriverPath = "";
    public static final String EdgeDriverPath = "";
    public static final String IEDriverPath = "";
    
    public static final String ScreenshotPath = "F:\\JavaCode\\KeyWordsDrivenTestFramework\\Screenshot\\";



}

ExcelUtil.java

package cn.summer.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;


import cn.summer.testScripts.TestSuiteByExcel;
import cn.summer.util.Constant;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelUtil {
	private static XSSFSheet ExcelWSheet;
	private static XSSFWorkbook ExcelWBook;
	private static XSSFCell Cell;
	private static XSSFRow Row;
	
	public static void setExcelFile(String Path) throws Exception{
		FileInputStream ExcelFile;
		try {
			ExcelFile = new FileInputStream(Path);
			ExcelWBook = new XSSFWorkbook(ExcelFile);
			
		}catch(Exception e) {
			TestSuiteByExcel.testResult = false;
			System.out.println("Excel路径设定失败");
			e.printStackTrace();
			//throw(e);
		}
	}
	public static void setExcelFile(String Path, String SheetName){
		FileInputStream ExcelFile;
		try {
			ExcelFile = new FileInputStream(Path);
			ExcelWBook = new XSSFWorkbook(ExcelFile);
			ExcelWSheet = ExcelWBook.getSheet(SheetName);
		}catch(Exception e) {
			TestSuiteByExcel.testResult = false;
			System.out.println("Excel路径设定失败");
			e.printStackTrace();
		}
	}
	
	//Read Excel文件指定单元格的函数,此函数只支持扩展名为“.xlsx的Excel”文件
	public static String getCellData(String SheetName, int RowNum, int ColNum){
		ExcelWSheet = ExcelWBook.getSheet(SheetName);
		try {
			Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
			String CellData = Cell.getCellType()==XSSFCell.CELL_TYPE_STRING ? 
					Cell.getStringCellValue() + "":String.valueOf(Math.round(Cell.getNumericCellValue()));
			
			return CellData;
		}catch(Exception e) {
			TestSuiteByExcel.testResult = false;
			e.printStackTrace();
			return "";
		}
	}
	public static void setCellData(String SheetName, int RowNum, int ColNum, String Result){
		ExcelWSheet = ExcelWBook.getSheet(SheetName);
		try {
			Row = ExcelWSheet.getRow(RowNum);
			Cell = Row.getCell(ColNum, Row.RETURN_BLANK_AS_NULL);
			
			if(Cell == null) {
				Cell = Row.createCell(ColNum);
				Cell.setCellValue(Result);
			}else {
				Cell.setCellValue(Result);
			}
			FileOutputStream fileOut = new FileOutputStream(Constant.Excel_FilePath);
			ExcelWBook.write(fileOut);
			fileOut.flush();
			fileOut.close();
		}catch(Exception e) {
			TestSuiteByExcel.testResult = false;
			e.printStackTrace();
			
		}
	}		
	public static int getlastColumnNum() {
		return ExcelWSheet.getRow(0).getLastCellNum()-1;
	}
	public static int getLastRowNum() {
		
		return ExcelWSheet.getLastRowNum();
	}
	public static int getRowCount(String SheetName) {
		ExcelWSheet = ExcelWBook.getSheet(SheetName);
		int number = ExcelWSheet.getLastRowNum();
		return number;
	}
	public static int getFirstRowContainsTestCaseID(String sheetName, String testCaseName, int colNum){
		int i;
		try {		
			ExcelWSheet = ExcelWBook.getSheet(sheetName);		
			int rowCount = ExcelUtil.getRowCount(sheetName);		
			for(i = 0; i<rowCount; i++) {			
				if(ExcelUtil.getCellData(sheetName, i, colNum).equalsIgnoreCase(testCaseName)) {				
					break;			
				}		
			}		
			return i;	
		}catch(Exception e) {
			TestSuiteByExcel.testResult = false;
			return 0;
		}
	}	
	public static int getTestCaseLastStepRow(String SheetName, String testCaseID, int testCaseStartRowNumber){
		try {		
			ExcelWSheet = ExcelWBook.getSheet(SheetName);		
			for(int i = testCaseStartRowNumber; i<=ExcelUtil.getRowCount(SheetName)-1; i++) {			
				if(!testCaseID.equals(ExcelUtil.getCellData(SheetName,i, Constant.Col_TestCaseID))) {				
					int number = i;				
					return number;			
				}		
			}		
			int number = ExcelWSheet.getLastRowNum()+1;		
			return number;	
		}catch(Exception e) {		
			TestSuiteByExcel.testResult = false;		
			return 0;
		}
	}
}

DataUtil.java

package cn.summer.util;

public class DateUtil {
	public static String format(java.util.Date date, String format) {
		String result = "";
		try {
			if(date != null) {
				java.text.DateFormat df = new java.text.SimpleDateFormat(format);
				result = df.format(date);
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	public static int getYear(java.util.Date date) {
		java.util.Calendar c = java.util.Calendar.getInstance();
		c.setTime(date);
		return c.get(java.util.Calendar.YEAR);
	}
	public static int getMonth(java.util.Date date) {
		java.util.Calendar c = java.util.Calendar.getInstance();
		c.setTime(date);
		return c.get(java.util.Calendar.MONTH)+1;
	}
	public static int getDay(java.util.Date date) {
		java.util.Calendar c = java.util.Calendar.getInstance();
		c.setTime(date);
		return c.get(java.util.Calendar.DAY_OF_MONTH);
	}
	public static int getHour(java.util.Date date) {
		java.util.Calendar c = java.util.Calendar.getInstance();
		c.setTime(date);
		return c.get(java.util.Calendar.HOUR_OF_DAY);
	}
	public static int getMinute(java.util.Date date) {
		java.util.Calendar c = java.util.Calendar.getInstance();
		c.setTime(date);
		return c.get(java.util.Calendar.MINUTE);
	}
	public static int getSecond(java.util.Date date) {
		java.util.Calendar c = java.util.Calendar.getInstance();
		c.setTime(date);
		return c.get(java.util.Calendar.SECOND);
	}

}

FileUtil.java

package cn.summer.util;

import java.io.File;
import java.io.IOException;

public class FileUtil {
	public static boolean createFile(String destFileName) {
		File file = new File(destFileName);
		if(file.exists()) {
			System.out.println("创建单个文件"+destFileName+"失败,目标文件已存在!");
			return false;
			
		}
		if(destFileName.endsWith(File.separator)) {
			System.out.println("创建单个文件"+destFileName+"失败,目标文件不能为目录!");
			return false;
		}
		if(!file.getParentFile().exists()){
			System.out.println("目标文件所在目录不存在,准备创建它!");
			if(!file.getParentFile().mkdirs()) {
				System.out.println("创建目标文件所在目录失败!");
				return false;
			}
		}
		try {
			if(file.createNewFile()) {
				System.out.println("创建单个文件"+destFileName+"成功!");
				return true;
			}else{
				System.out.println("创建单个文件"+destFileName+"失败!");
				return false;
			}
		}catch(IOException e) {
			e.printStackTrace();
			System.out.println("创建单个文件"+destFileName+"失败!"+e.getMessage());
			return false;
			
		}
	}

	public static boolean createDir(String destDirName) {
		File dir = new File(destDirName);
		if(dir.exists()) {
			System.out.println("创建目录"+destDirName+"失败,目标目录已经存在");
			return false;
		}
		if(dir.mkdirs()) {
			System.out.println("创建目录"+destDirName+"成功!");
			return true;
		}else {
			System.out.println("创建目录"+destDirName+"失败!");
			return false;
		}
	}
}

ImageComparison.java

package cn.summer.util;

import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.testng.Assert;

public class ImageComparison {
	
	
	public static void imageComparison(File fileInput, File fileOutPut) throws IOException, InterruptedException{
		BufferedImage bufileInput = ImageIO.read(fileInput);
		DataBuffer dafileInput = bufileInput.getData().getDataBuffer();
		int sizefileInput = dafileInput.getSize();
		BufferedImage bufileOutPut = ImageIO.read(fileOutPut);
		
		DataBuffer dafileOutPut = bufileOutPut.getData().getDataBuffer();
		int sizefileOutPut = dafileOutPut.getSize();
		Boolean matchFlag = true;
		if (sizefileInput==sizefileOutPut) {
			for(int j = 0;j<sizefileInput;j++) {
				if(dafileInput.getElem(j)!=dafileOutPut.getElem(j)) {
					matchFlag = false;
					break;
				}
			}
		}else
			matchFlag = false;
		Assert.assertTrue(matchFlag, "测试过程中的截图和期望的截图并不一致");
		Log.info("测试过程中的截图和期望的截图并不一致");
	}

}

KeyBoardUtil.java

package cn.summer.util;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;

public class KeyBoardUtil {
	public static void pressTabKey() {	
		Robot robot = null;	
		try {		
			robot = new Robot();			
		}catch(AWTException e) {		
			e.printStackTrace();
	
		}
		robot.keyPress(KeyEvent.VK_TAB);
		robot.keyRelease(KeyEvent.VK_TAB);
	}
	public static void pressEnterKey() {	
		Robot robot = null;	
		try {		
			robot = new Robot();			
		}catch(AWTException e) {		
			e.printStackTrace();
	
		}
		robot.keyPress(KeyEvent.VK_ENTER);
		robot.keyRelease(KeyEvent.VK_ENTER);
	}
	public static void setAndctrlVClipboardData(String string) {
		StringSelection stringSelection = new StringSelection(string);
		Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);	
		Robot robot = null;
		try {
			robot = new Robot();
			
		}catch(AWTException e1) {
			e1.printStackTrace();
		}
		robot.keyPress(KeyEvent.VK_CONTROL);
		robot.keyPress(KeyEvent.VK_V);
		robot.keyRelease(KeyEvent.VK_V);
		robot.keyRelease(KeyEvent.VK_CONTROL);
	}
}

Log.java

package cn.summer.util;
import org.apache.log4j.Logger;

public class Log {
	private static Logger Log = Logger.getLogger(Log.class.getName());
	
	public static void startTestCase(String testCaseName) {
		Log.info("------------------------\""+testCaseName+"\"      start running ----------------");
	}
	public static void endTestCase(String testCaseName) {
		Log.info("------------------------\""+testCaseName+"\"      Test Ended--------------------");
	}
	public static void info(String message) {
		Log.info(message);
	}
	public static void warn(String message) {
		Log.info(message);
	}
	public static void error(String message) {
		Log.info(message);
	}
	public static void debug(String message) {
		Log.info(message);
	}
	public static void fatal(String message) {
		Log.info(message);
	}

}

ObjectMap.java

package cn.summer.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Properties;

import org.openqa.selenium.By;

public class ObjectMap {
	Properties properties;
	public ObjectMap(String propFile) {
		properties = new Properties();
		try {
			Reader in = new InputStreamReader(new FileInputStream(propFile),"UTF-8");
			properties.load(in);
			in.close();
		}catch(IOException e) {
			Log.info("读取Object文件异常,具体异常信息为: "+e.getMessage());
			e.printStackTrace();
		}
	}
	
	public By getLocator(String ElementNameInpropFile) throws Exception{
		String locator = properties.getProperty(ElementNameInpropFile);
		String locatorType = locator.split(">")[0];
		String locatorValue = locator.split(">")[1];
		//Log.info("获取的定位类型: " + locatorType + "\t 获取的定位表达式: " + locatorValue);
		if(locatorType.toLowerCase().equals("id"))
			return By.id(locatorValue);		
		else if(locatorType.toLowerCase().equals("name"))
			return By.name(locatorValue);		
		else if((locatorType.toLowerCase().equals("classname")) ||
		(locatorType.toLowerCase().equals("class")))
			return By.className(locatorValue);		
		else if((locatorType.toLowerCase().equals("tagname")) ||
				(locatorType.toLowerCase().equals("tag")))
			return By.className(locatorValue);		
		else if((locatorType.toLowerCase().equals("linktext")) ||
				(locatorType.toLowerCase().equals("link")))
			return By.linkText(locatorValue);		
		else if(locatorType.toLowerCase().equals("partiallinktext"))
			return By.partialLinkText(locatorValue);		
		else if((locatorType.toLowerCase().equals("cssselector"))||
		(locatorType.toLowerCase().equals("css")))
			return By.cssSelector(locatorValue);
		else if(locatorType.toLowerCase().equals("xpath"))
			return By.xpath(locatorValue);
		else
			throw new Exception("输入的locator type未在程序中被定义: " + locatorType);
		
	}

}


TakeScreenshotUtil.java

package cn.summer.util;

import java.io.File;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class TakeScreenshotUtil {
	public static void takeScreenshot(WebDriver driver) {
		try {
			Date date = new Date();
			String picDir = "D:\\"+String.valueOf(DateUtil.getYear(date))+"-"
			     +String.valueOf(DateUtil.getMonth(date))+"-"+String.valueOf(DateUtil.getDay(date));
			if(!new File(picDir).exists()) {
				FileUtil.createDir(picDir);
			}
			String filePath = picDir +"\\"+String.valueOf(DateUtil.getHour(new Date()))+"-"
			    +String.valueOf(DateUtil.getMinute(new Date()))+"-"
				+String.valueOf(DateUtil.getSecond(new Date()))+".png";
		
			File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
			FileUtils.copyFile(srcFile, new File(filePath));
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	public static void takeScreenshotWithElement(WebDriver driver, WebElement element) {
		
	}

}

WaitUtil.java

package cn.summer.util;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class WaitUtil {

	public static void sleep(long millisecond) {
		try {
			Thread.sleep(millisecond);
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	public static void waitWebElement(WebDriver driver,String xpathExpression) {
		WebDriverWait wait = new WebDriverWait(driver,10);
		wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpathExpression)));
	}
	public static void waitWebElement(WebDriver driver,By by) {
		WebDriverWait wait = new WebDriverWait(driver,10);
		wait.until(ExpectedConditions.presenceOfElementLocated(by));
	}
}

在工程下创建log4j.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
<appender name="fileAppender" class="org.apache.log4j.FileAppender">
<param name="Threshold" value="INFO"/>
<param name="File" value="OWATestLogfile.log"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p [%c{1}] %m %n"/>
</layout>
</appender>
<root>
<level value="INFO"/>
<appender-ref ref="fileAppender"/>
</root>
</log4j:configuration>

在工程下创建OWATestLogfile.log文件。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Summer@123

不积跬步无以至千里,感谢支持!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值