Java自动化测试系列[v1.0.0][关键字驱动]

关键字驱动框架在很多领域应用较为广泛,实际上它仍是一种分离的思想,测试代码在编译时根本无法预知对象和类属于哪些类实际上也无需关心,完全可以依靠运行时信息来发现该对象和类的真实信息,使用Java的反射技术进行获取,益处多多

关键字分离

关键字驱动的设计起始就在于关键字的设计
在这里插入图片描述

解析关键字数据

关键字蕴藏的是设计思想,那么解析关键字就是将思想逐渐分解

package util;
/*
 * 描述:The method of parseExcel
 *
 * @author davieyang
 * @create 2018-08-05 0:37
 */

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

import constants.Constants;
import org.apache.poi.ss.usermodel.CellType;
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 ParseExcelUtil {
    private static XSSFSheet ExcelWSheet;
    private static XSSFWorkbook ExcelWBook;
    private static XSSFCell Cell;
    private static XSSFRow Row;

    /**
     * 读取要操作的Excel的文件
     * @param Path:Excel文件绝对路径
     */
    public static void setExcelFile(String Path){
        FileInputStream ExcelFile;
        try{
            //实例化Excel文件的FileInputStream对象
            ExcelFile = new FileInputStream(Path);
            //实例化Excel文件的XSSFWorkbook对象
            ExcelWBook = new XSSFWorkbook(ExcelFile);
        }catch (Exception e){
            System.out.println("Excel路径设定失败");
            e.printStackTrace();
        }
    }

    /**
     * 设定要读取的Excel路径和Excel文件中Sheet名称
     * @param Path 文件路径
     * @param SheetName 表单名称
     */
    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) {
            System.out.println("Excel 路径设定失败");
            e.printStackTrace();
        }
    }

    /**
     * 读取Excel文件指定的单元格函数,此函数只支持扩展名为xlsx的Excel文件
     * @param rowNum 行号
     * @param colNum 列号
     * @return 返回单元格对象
     */
    public static Object getCellData(int rowNum, int colNum) {
        Object CellData;
        try {
            //通过函数参数指定单元格的行号和列号,获取指定的单元格对象
            Cell = ExcelWSheet.getRow(rowNum).getCell(colNum);
            CellData = "";
            //如果单元格内容为字符串类型,则使用getStringCellValue方法获取单元格的内容
            //如果单元格内容为数字类型,则使用getNumericCellValue方法获取单元格的内容
            if (Cell.getCellTypeEnum() == CellType.STRING) {
                CellData = Cell.getStringCellValue();
            } else if (Cell.getCellTypeEnum() == CellType.NUMERIC) {
                CellData = Cell.getNumericCellValue();
            }
            return CellData;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 读取指定sheet中的指定单元格函数,此函数只支持.xlsx
     * @param sheetName 表单名称
     * @param rowNum 行号
     * @param colNum 列号
     * @return 返回单元格内字符串
     */
    public static String getCellData(String sheetName, int rowNum, int colNum){
         ExcelWSheet = ExcelWBook.getSheet(sheetName);
         try{
             //通过函数的参数指定单元格的行号和列号,获取指定单元格对象
             Cell = ExcelWSheet.getRow(rowNum).getCell(colNum);
             String CellData = null;
             if (Cell.getCellTypeEnum() == CellType.STRING) {
                 CellData = Cell.getStringCellValue();
             }else if (Cell.getCellTypeEnum() == CellType.NUMERIC){
                 CellData = String.valueOf(Math.round(Cell.getNumericCellValue()));
             }
             return CellData;
         }catch (Exception e){
             e.printStackTrace();
             return "";
         }
    }

    /**
     * @param sheetName 表单名称
     * @return 获取指定Sheet中数据的总行数
     */
    public static int getRowCount(String sheetName){
        ExcelWSheet = ExcelWBook.getSheet(sheetName);
        int RowCount = ExcelWSheet.getLastRowNum();
        return RowCount;
    }
    public static int getLastRowNum() {
        return ExcelWSheet.getLastRowNum();
    }

    /**
     * @param sheetName 表单名称
     * @param testCaseName 测试用例mine工程
     * @param colNum 列号
     * @return 在Excel的指定Sheet中,获取第一次包含指定测试用例序号文字的行号
     */
    public static int getFirstRowContainsTestCaseID(String sheetName, String testCaseName, int colNum) {
        int i;
        try {
            ExcelWSheet = ExcelWBook.getSheet(sheetName);
            int rowCount = ParseExcelUtil.getRowCount(sheetName);
            for (i = 0; i < rowCount; i++) {
                //使用循环遍历测试用例列的所有行的方法,判断是否包含某个测试用例序号关键字
                if (ParseExcelUtil.getCellData(sheetName, i, colNum).equalsIgnoreCase(testCaseName)) {
                    //如果包含则退出for循环,并返回包含测试用例序号关键字的行号
                    break;
                }
            }
            return i;
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * @param sheetName 表单名称
     * @param testCaseID 测试用例ID
     * @param testCaseStartRowNumber 测试用例启示行号
     * @return 获取指定Sheet中某个测试用例步骤的个数
     */
    public static int getTestCaseLastStepRow(String sheetName, String testCaseID, int testCaseStartRowNumber) {
        try {
            ExcelWSheet = ExcelWBook.getSheet(sheetName);
            /*从包含指定测试用例序号的第一行开始逐行遍历,直到某一行不出现指定测试用例序号
             *此时的遍历次数就是此测试用例步骤的个数
             */
            for (int i = testCaseStartRowNumber; i <= ParseExcelUtil.getRowCount(sheetName) - 1; i++) {
                if (!testCaseID.equals(ParseExcelUtil.getCellData(sheetName, i, Constants.Col_TestCaseID))) {
                    int number = i;
                    return number;
                }
            }
            int number = ExcelWSheet.getLastRowNum() + 1;
            return number;
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 在Excel指定单元格中写入输入,只支持xlsx
     * @param SheetName 表单名称
     * @param RowNum 行号
     * @param ColNum 列号
     * @param Result 结果
     */
    public static void setCellData(String SheetName, int RowNum, int ColNum, String Result){
        ExcelWSheet = ExcelWBook.getSheet(SheetName);
        try{
            //获取Excel中的行对象
            Row = ExcelWSheet.getRow(RowNum);
            //如果单元格为空则返回Null
            Cell = Row.getCell(ColNum, org.apache.poi.ss.usermodel.Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
            if (Cell == null){
                //当单元格为null时创建单元格
                //如果单元格为空,无法直接调用单元格对象的setCellValue方法设定单元格的值
                Cell = Row.createCell(ColNum);
                //创建单元格后,可以直接调用单元格对象的setCellValue方法设定单元格的值
                Cell.setCellValue(Result);
            }else {
                //单元格中有内容,则可以直接调用单元格对象的setCellValue方法设定单元格的值
                Cell.setCellValue(Result);
            }
            //实例化写入Excel文件的文件输出流对象
            FileOutputStream fileOutputStream = new FileOutputStream(Constants.Path_ExcelFile);
            //将内容写入到Excel文件中
            ExcelWBook.write(fileOutputStream);
            //调用flush方法强制刷新写入文件
            fileOutputStream.flush();
            //关闭文件输出流
            fileOutputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}



package Util;
/**
 * 描述:
 * The method of parseExcel
 *
 * @author davieyang
 * @create 2018-08-05 0:37
 */

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

import Configurations.Constants;
import org.apache.poi.ss.usermodel.CellType;
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;
import TestScripts.TestSuiteByExcel;

public class ParseExcelUtil {
    private static XSSFSheet ExcelWSheet;
    private static XSSFWorkbook ExcelWBook;
    private static XSSFCell Cell;
    private static XSSFRow Row;

    //设定要操作的Excel的文件路径
    public static void setExcelFile(String Path){
        FileInputStream ExcelFile;
        try{
            //实例化Excel文件的FileInputStream对象
            ExcelFile = new FileInputStream(Path);
            //实例化Excel文件的XSSFWorkbook对象
            ExcelWBook = new XSSFWorkbook(ExcelFile);
        }catch (Exception e){
            TestSuiteByExcel.testResult = false;
            System.out.println("Excel路径设定失败");
            e.printStackTrace();
        }
    }
    //设定要读取的Excel路径和Excel文件中Sheet名称
    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();
        }
    }

    //读取Excel文件指定的单元格函数,此函数只支持扩展名为xlsx的Excel文件
    public static Object getCellData(int rowNum, int colNum) {
        Object CellData;
        try {
            //通过函数参数指定单元格的行号和列号,获取指定的单元格对象
            Cell = ExcelWSheet.getRow(rowNum).getCell(colNum);
            CellData = "";
            //如果单元格内容为字符串类型,则使用getStringCellValue方法获取单元格的内容
            //如果单元格内容为数字类型,则使用getNumericCellValue方法获取单元格的内容
            if (Cell.getCellTypeEnum() == CellType.STRING) {
                CellData = Cell.getStringCellValue();
            } else if (Cell.getCellTypeEnum() == CellType.NUMERIC) {
                CellData = Cell.getNumericCellValue();
            }
            return CellData;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    //读取指定sheet中的指定单元格函数,此函数只支持.xlsx
    public static String getCellData(String sheetName, int rowNum, int colNum){
         ExcelWSheet = ExcelWBook.getSheet(sheetName);
         try{
             //通过函数的参数指定单元格的行号和列号,获取指定单元格对象
             Cell = ExcelWSheet.getRow(rowNum).getCell(colNum);
             String CellData = null;
             if (Cell.getCellTypeEnum() == CellType.STRING) {
                 CellData = Cell.getStringCellValue();
             }else if (Cell.getCellTypeEnum() == CellType.NUMERIC){
                 CellData = String.valueOf(Math.round(Cell.getNumericCellValue()));
             }
             return CellData;
         }catch (Exception e){
             TestSuiteByExcel.testResult = false;
             e.printStackTrace();
             return "";
         }
    }
    //获取指定Sheet中数据的总行数
    public static int getRowCount(String sheetName){
        ExcelWSheet = ExcelWBook.getSheet(sheetName);
        int RowCount = ExcelWSheet.getLastRowNum();
        return RowCount;
    }
    public static int getLastRowNum() {
        return ExcelWSheet.getLastRowNum();
    }
    //在Excel的指定Sheet中,获取第一次包含指定测试用例序号文字的行号
    public static int getFirstRowContainsTestCaseID(String sheetName, String testCaseName, int colNum) {
        int i;
        try {
            ExcelWSheet = ExcelWBook.getSheet(sheetName);
            int rowCount = ParseExcelUtil.getRowCount(sheetName);
            for (i = 0; i < rowCount; i++) {
                //使用循环遍历测试用例列的所有行的方法,判断是否包含某个测试用例序号关键字
                if (ParseExcelUtil.getCellData(sheetName, i, colNum).equalsIgnoreCase(testCaseName)) {
                    //如果包含则退出for循环,并返回包含测试用例序号关键字的行号
                    break;
                }
            }
            return i;
        } catch (Exception e) {
            TestSuiteByExcel.testResult = false;
            return 0;
        }
    }
    //获取指定Sheet中某个测试用例步骤的个数
    public static int getTestCaseLastStepRow(String sheetName, String testCaseID, int testCaseStartRowNumber) {
        try {
            ExcelWSheet = ExcelWBook.getSheet(sheetName);
            /*从包含指定测试用例序号的第一行开始逐行遍历,直到某一行不出现指定测试用例序号
             *此时的遍历次数就是此测试用例步骤的个数
             */
            for (int i = testCaseStartRowNumber; i <= ParseExcelUtil.getRowCount(sheetName) - 1; i++) {
                if (!testCaseID.equals(ParseExcelUtil.getCellData(sheetName, i, Constants.Col_TestCaseID))) {
                    int number = i;
                    return number;
                }
            }
            int number = ExcelWSheet.getLastRowNum() + 1;
            return number;
        } catch (Exception e) {
            TestSuiteByExcel.testResult = false;
            return 0;
        }
    }
    //在Excel指定单元格中写入输入,只支持xlsx
    public static void setCellData(String SheetName, int RowNum, int ColNum, String Result){
        ExcelWSheet = ExcelWBook.getSheet(SheetName);
        try{
            //获取Excel中的行对象
            Row = ExcelWSheet.getRow(RowNum);
            //如果单元格为空则返回Null
            Cell = Row.getCell(ColNum, org.apache.poi.ss.usermodel.Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
            if (Cell == null){
                //当单元格为null时创建单元格
                //如果单元格为空,无法直接调用单元格对象的setCellValue方法设定单元格的值
                Cell = Row.createCell(ColNum);
                //创建单元格后,可以直接调用单元格对象的setCellValue方法设定单元格的值
                Cell.setCellValue(Result);
            }else {
                //单元格中有内容,则可以直接调用单元格对象的setCellValue方法设定单元格的值
                Cell.setCellValue(Result);
            }
            //实例化写入Excel文件的文件输出流对象
            FileOutputStream fileOutputStream = new FileOutputStream(Constants.Path_ExcelFile);
            //将内容写入到Excel文件中
            ExcelWBook.write(fileOutputStream);
            //调用flush方法强制刷新写入文件
            fileOutputStream.flush();
            //关闭文件输出流
            fileOutputStream.close();
        }catch (Exception e){
            TestSuiteByExcel.testResult = false;
            e.printStackTrace();
        }

    }
}

分离工具类

package Util;
/**
 * 描述:
 * The method of common
 *
 * @author davieyang
 * @create 2018-08-05 0:37
 */
import static Configurations.Constants.Path_BrowserDrivers;
import static Util.LogUtil.info;
import static Util.WaitElementUntil.waitWebElementPresence;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import Configurations.Constants;
import org.apache.log4j.xml.DOMConfigurator;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import TestScripts.TestSuiteByExcel;


public class KeyWordsAction {
    private static WebDriver driver;
    private static GetElementsUtil getElementsUtil = new GetElementsUtil(Constants.Path_ConfigurationFile);
    static {
        //指定log4j配置文件为log4j.xml
        DOMConfigurator.configure("log4j.xml");
    }
    /**
     *定义函数initBrowser,并返回驱动, 参数String为无实际值传入的参数,仅为了通过反射机制统一的使用两个函数参数调用此函数
     */

    //方法名对应Excel文件中的“关键字”列中的open_browser关键字,Excel“操作值”列中的内容用于指定用何种浏览器,也就是本函数的参数
    public static WebDriver open_browser(String browserName, String string) {
        if(browserName.equalsIgnoreCase("chrome")) {
            System.setProperty("webdriver.chrome.driver",Path_BrowserDrivers + "chromedriver.exe");
            driver = new ChromeDriver();
            LogUtil.info("启动Chrome浏览器");
        }else if (browserName.equalsIgnoreCase("ie")){
            System.setProperty("webdriver.ie.driver",Path_BrowserDrivers + "IEDriverServer.exe");
            driver = new InternetExplorerDriver();
            LogUtil.info("启动IE浏览器");
        }else {
            System.setProperty("webdriver.gecko.driver", Path_BrowserDrivers + "geckodriver.exe");
            driver = new FirefoxDriver();
            LogUtil.info("启动Firefox浏览器");
        }
        return driver;
    }
    /**
     *定义函数navigate, 参数String为无实际值传入的参数,仅为了通过反射机制统一的使用两个函数参数调用此函数
     */
    //对应Excel文件中“关键字”列的navigate关键字
    public static void navigate(String url, String string) {
        driver.get(url);
        LogUtil.info("访问" + url);
    }
    /**
     *定义函数input,参数String为无实际值传入的参数,仅为了通过反射机制统一的使用两个函数参数调用此函数
     */
    //对应Excel文件中“关键字列”的input关键字
    public static void input(String locatorExpression, String inputString) {
        System.out.println("收到用户名输入:" + inputString);
        try {
            driver.findElement(getElementsUtil.getLocator(locatorExpression)).clear();
            LogUtil.info("清除" + locatorExpression + "输入框的所有内容");
            driver.findElement(getElementsUtil.getLocator(locatorExpression)).sendKeys(inputString);
            LogUtil.info("在" + locatorExpression + "输入框中输入:" + inputString);
        } catch (Exception e) {
            TestSuiteByExcel.testResult = false;
            LogUtil.info("在" + locatorExpression + "输入框中输入" + inputString + "时出现异常,异常信息为:" + e.getMessage());
            e.printStackTrace();
        }
    }
    /**
     *定义函数click,参数String为无实际值传入的参数,仅为了通过反射机制统一的使用两个函数参数调用此函数
     */
    public static void click(String locatorExpression, String string){
        try{
            driver.findElement(getElementsUtil.getLocator(locatorExpression)).click();
            LogUtil.info("点击" + locatorExpression + "页面元素成功");
        }catch (Exception e){
            TestSuiteByExcel.testResult = false;
            LogUtil.info("单击" + locatorExpression + "页面元素出现异常,异常信息为:" + e.getMessage());
            e.printStackTrace();
        }
    }
    /**
     *定义函数WaitFor_Element,参数String为无实际值传入的参数,仅为了通过反射机制统一的使用两个函数参数调用此函数
     */
    public static void WaitFor_Element(String locatorExpression, String string){
        try{
            waitWebElementPresence(driver, getElementsUtil.getLocator(locatorExpression));
            LogUtil.info("显示等待页面元素出现成功, 页面元素是" + locatorExpression);
        }catch (Exception e){
            TestSuiteByExcel.testResult = false;
            LogUtil.info("显示等待页面元素时出现异常,异常信息为:" + e.getMessage());
            e.printStackTrace();
        }
    }
    /**
     *定义函数press_Tab,参数String为无实际值传入的参数,仅为了通过反射机制统一的使用两个函数参数调用此函数
     */
    public static void press_Tab(String string1, String string2){
        try{
            Thread.sleep(2000);
            KeyBoardUtil.PressTabKey();
            LogUtil.info("按Tab键成功");
        } catch (Exception e) {
            TestSuiteByExcel.testResult = false;
            LogUtil.info("按Tab键出现异常,异常信息为:" + e.getMessage());
            e.printStackTrace();

        }
    }
    /**
     *定义函数pasteString,参数String为无实际值传入的参数,仅为了通过反射机制统一的使用两个函数参数调用此函数
     */
    public static void pasteString(String pasteContent, String string){
        try{
            KeyBoardUtil.setAndCtrlVClipboardData(pasteContent);
            LogUtil.info("成功黏贴内容:" + pasteContent);
        }catch (Exception e){
            TestSuiteByExcel.testResult = false;
            LogUtil.info("黏贴内容时出现异常,具体异常信息为:" + e.getMessage());
            e.printStackTrace();
        }
    }
    /**
     *定义函数press_enter,参数String为无实际值传入的参数,仅为了通过反射机制统一的使用两个函数参数调用此函数
     */
    public static void press_enter(String string1, String string2){
        try{
            KeyBoardUtil.PressEnterKey();
            LogUtil.info("按回车键成功");
        }catch (Exception e){
            TestSuiteByExcel.testResult = false;
            LogUtil.info("按回车键出现异常,具体异常信息为:" + e.getMessage());
            e.printStackTrace();
        }
    }
    /**
     *定义函数sleep,参数String为无实际值传入的参数,仅为了通过反射机制统一的使用两个函数参数调用此函数
     */
    public static void sleep(String sleepTime, String string){
        try{
            WaitElementUntil.sleep(Integer.parseInt(sleepTime));
            LogUtil.info("休眠"+ Integer.parseInt(sleepTime)/1000+"秒成功");
        }catch (Exception e){
            TestSuiteByExcel.testResult = false;
            LogUtil.info("线程休眠时出现异常,具体异常信息:"+ e.getMessage());
            e.printStackTrace();
        }
    }
    /**
     *定义函数click_sendMailButton,参数String为无实际值传入的参数,仅为了通过反射机制统一的使用两个函数参数调用此函数
     */
    public static void click_sendMailButton(String locatorExpression, String string){
        try{
            /*页面上存在两个发送按钮可执行发送功能,为了使用xpath匹配方便,
             *同时匹配了两个发送按钮,并存储在list容器中,再随便取出一个
             *按钮对象,来完成单击发送邮件按钮的操作
             */
            List<WebElement> buttons = driver.findElements(getElementsUtil.getLocator(locatorExpression));
            buttons.get(0).click();
            LogUtil.info("单击发送邮件按钮成功");
            System.out.println("发送按钮被成功点击");
        }catch (Exception e){
            TestSuiteByExcel.testResult = false;
            LogUtil.info("单击发送邮件按钮出现异常,异常信息为:" + e.getMessage());
            e.printStackTrace();
        }
    }
    /**
     *定义函数Assert_String,参数String为无实际值传入的参数,仅为了通过反射机制统一的使用两个函数参数调用此函数
     */
    public static void Assert_String(String assertString, String string){
        try{
            Assert.assertTrue(driver.getPageSource().contains(assertString));
            LogUtil.info("成功断言关键字“" + assertString +"”");
        }catch (AssertionError e){
            TestSuiteByExcel.testResult = false;
            LogUtil.info("断言失败,具体断言失败信息:" + e.getMessage());
            System.out.println("断言失败");
        }
    }
    /**
     *定义函数close_browser,参数String为无实际值传入的参数,仅为了通过反射机制统一的使用两个函数参数调用此函数
     */
    public static void close_browser(String string1, String string2){
        try{
            System.out.println("关闭浏览器");
            LogUtil.info("关闭浏览器窗口");
            driver.quit();
        }catch (Exception e){
            TestSuiteByExcel.testResult = false;
            LogUtil.info("关闭浏览器出现异常,异常信息为:" + e.getMessage());
            e.printStackTrace();
        }
    }
    //定义函数navigate,用于获取浏览器要访问的链接
    public static void navigate(String url){
        driver.get(url);
        info("访问地址为"+url);
    }
    //用于显示等待页面元素的出现
    public static void WaitFor_Element(String xpathExpression) throws Exception {
        By by = getElementsUtil.getLocator(xpathExpression);
        try{
            waitWebElementPresence(driver, by);
            info("显示等待页面元素出现成功, 页面元素是" + xpathExpression);
        }catch (Exception e){
            info("显示等待页面元素时出现异常,异常信息为:" + e.getMessage());
            e.printStackTrace();
        }
    }
    /**这是智能等待元素加载的方法*/
    public void intelligentWait(WebDriver driver,int timeOut, final By by) {
        try {
            (new WebDriverWait(driver, timeOut)).until(new ExpectedCondition<Boolean>() {
                public Boolean apply(WebDriver driver) {
                    WebElement element = driver.findElement(by);
                    return element.isDisplayed();
                }
            });


        } catch (TimeoutException e) {
            Assert.fail("超时L !! " + timeOut + " 秒之后还没找到元素 [" + by + "]", e);
        }
    }
    //通过从剪切板黏贴的方式,在文件上传框体的文件名输入框中输入要上传文件的路径和名称"uploadpathandname"
    public static void paste_uploadFilename(String uploadpathandname){
        try{
            KeyBoardUtil.setAndCtrlVClipboardData(uploadpathandname);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //页面上不止一个相同功能并且xpath相同的元素,此种情况处理是将他们存储到List中,然后用索引的方式用其一
    public static void twoWay(String ElementNameInproFile){
        try {
            List<WebElement> elements = driver.findElements(getElementsUtil.getLocator(ElementNameInproFile));
            elements.get(0).click();
            System.out.println("按钮被成功点击");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //用于等待操作,暂停几秒,函数参数以毫秒为单位
    public static void sleep(String sleepTime){
        try{
            WaitElementUntil.sleep(Integer.parseInt(sleepTime));
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //断言文字内容
    public static void assert_String(WebDriver driver,String assertstring){
        try{
            Assert.assertTrue(driver.getPageSource().contains(assertstring));
            info("成功断言关键字“"+ assertstring +"”");
        }catch (AssertionError e){
            info("断言失败,具体失败信息为:"+ e.getMessage());
            System.out.println("断言失败");
        }
    }
    //断言文字不存在
    public static void assert_NoString(WebDriver driver, String assertstring){
        try{
            Assert.assertFalse(driver.getPageSource().contains(assertstring));
            info("成功断言关键字“"+ assertstring +"” + “不存在”");
        }catch (AssertionError e){
            info("断言失败,具体信息为:" + e.getMessage());
            System.out.println("断言失败");
        }
    }

    //关闭浏览器
    public static void close_Browser(WebDriver driver){
        try{
            System.out.println("关闭浏览器");
            driver.quit();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public static WebDriver caseBrowser(String browser) {
        switch (browser) {
            case "ie":
                System.setProperty("webdriver.ie.driver",Path_BrowserDrivers+"IEDriverServer.exe");
                driver = new InternetExplorerDriver();
                break;
            case "firefox":
                System.setProperty("webdriver.gecko.driver", Path_BrowserDrivers+"geckodriver.exe");
                driver = new FirefoxDriver();
                break;
            case "chrome":
                System.setProperty("webdriver.chrome.driver",Path_BrowserDrivers+"chromedriver.exe");
                driver = new ChromeDriver();
                break;
            default:
                try {
                    throw new Exception("浏览器错误!");
                } catch (Exception e) {
                    e.printStackTrace();
                }
        }
        return driver;
    }
    public static void openBrowser(String url, String browser, int timeOutInSeconds) {
        driver = open_browser(browser, "davieyang");
        driver.manage().timeouts().implicitlyWait(timeOutInSeconds, TimeUnit.SECONDS);
        driver.get(url);
    }
    public static void selectByValue(String string, String value) {
        Select select = new Select(driver.findElement(By.xpath(string)));
        select.selectByValue(value);
    }
    public static void selectByText(String string, String text) {
        Select select = new Select(driver.findElement(By.xpath(string)));
        select.selectByVisibleText(text);
    }
    public static void selectByIndex(String string, int index) {
        Select select = new Select(driver.findElement(By.xpath(string)));
        select.selectByIndex(index);
    }
    public static void switchToFrame(By locator) {
        driver.switchTo().frame(driver.findElement(locator));
    }
    public static void switchToParentFrame() {
        driver.switchTo().defaultContent();
    }
    public static void dismissAlert() {
        Alert alert = driver.switchTo().alert();
        alert.dismiss();
    }
    public static void acceptAlert() {
        Alert alert = driver.switchTo().alert();
        alert.accept();
    }
    public static String getAlertText() {
        Alert alert = driver.switchTo().alert();
        return alert.getText();
    }
    public static void inputTextToAlert(String text) {
        Alert alert = driver.switchTo().alert();
        alert.sendKeys(text);
    }
    public static void deleteCookie(String name) {
        driver.manage().deleteCookieNamed(name);
    }

    public static void deleteAllCookies() {
        driver.manage().deleteAllCookies();
    }
    public static Map<String, String> getCookieByName(String name) {
        Cookie cookie = driver.manage().getCookieNamed(name);
        if (cookie != null) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("name", cookie.getName());
            map.put("value", cookie.getValue());
            map.put("path", cookie.getPath());
            map.put("domain", cookie.getDomain());
            map.put("expiry", cookie.getExpiry().toString());
            return map;
        }
        return null;
    }
    public static Set<Cookie> getAllCookies() {
        return driver.manage().getCookies();
    }
    public static void addCookie(String name, String value) {
        driver.manage().addCookie(new Cookie(name, value));
    }
    public static void addCookie(String name, String value, String path) {
        driver.manage().addCookie(new Cookie(name, value, path));
    }

    public static void closeCurrentBrowser(WebDriver driver) {
        driver.close();
        info("关闭浏览器...");
    }

    public static void closeAllBrowser(WebDriver driver) {
        driver.quit();
        info("关闭浏览器...");
    }

    public static void maxBrowser(WebDriver driver) {
        driver.manage().window().maximize();
        info("浏览器最大化...");
    }
    public static void setBrowserSize(int width, int height) {
        driver.manage().window().setSize(new Dimension(width, height));
        info("设置浏览器为" + width + "高度为" + height);
    }
    /**获取当前URL*/
    public static String getURL(WebDriver driver) {
        return driver.getCurrentUrl();
    }
    /**获取当前浏览器页面的标题*/
    public static String getTitle(WebDriver driver) {
        return driver.getTitle();
    }
    public void returnToPreviousPage() {
        driver.navigate().back();
        LogUtil.info("返回到上一个页面...");
    }
    /**在浏览器的历史中向前到下一个页面, 如果我们在最新的页面上看, 什么也不做, 即点击浏览器下一页*/
    public void forwardToNextPage() {
        driver.navigate().forward();
        LogUtil.info("Link到下一个页面...");
    }
    public static void refreshPage() {
        driver.navigate().refresh();
        LogUtil.info("刷新页面");
    }

    /**WebDriver切换到当前页面*/
    public static void switchToCurrentPage() {
        String handle = driver.getWindowHandle();
        for (String tempHandle : driver.getWindowHandles()) {
            if(tempHandle.equals(handle)) {
                driver.close();
            }else {
                driver.switchTo().window(tempHandle);
            }
        }
    }

    public static String getElementText(By locator) {
        return driver.findElement(locator).getText();
    }

    public static void clearText(By locator) {
        driver.findElement(locator).clear();
    }

    public static void submitForm(By locator) {
        driver.findElement(locator).submit();
    }

    public static void uploadFile(By locator, String filePath) {
        driver.findElement(locator).sendKeys(filePath);
    }
}

关键字驱动测试代码

package TestScripts;
import Util.ParseExcelUtil;
import Util.KeyWordsAction;
import Configurations.Constants;
import org.junit.Assert;
import org.testng.annotations.Test;
import java.lang.reflect.Method;

public class TestSendMailWithAttachmentByExcel {
    public static Method method[];
    public static Object keyword;
    public static Object value;
    public static KeyWordsAction keyWordsAction;
    @Test
    public void testSendMailWithAttachment()throws Exception{
        /*声明一个关键字类对象
         *使用java的反射机制获取KeyWordsAction类中的所有方法对象
         */
        keyWordsAction = new KeyWordsAction();
        method = keyWordsAction.getClass().getMethods();
        //设定Excel文件中"发送邮件"sheet为操作目标
        ParseExcelUtil.setExcelFile(Constants.Path_ExcelFile, Constants.Sheet_TestSteps);
        /*从Excel文件的"发送邮件"sheet中,将每一行的第四列读取出来作为关键字信息
         *通过遍历比较的方法,执行关键字在KeyWordsAction类中对应的映射方法
         *将每一行的第五列读取出来作为映射方法的函数参数
         * 调用execute_Actions函数完成映射方法的调用执行过程
         */
        for (int iRow = 1; iRow <=ParseExcelUtil.getLastRowNum(); iRow++){
            //读取sheet中的第四列
            keyword = ParseExcelUtil.getCellData(iRow, Constants.Col_KeyWordAction);
            //读取sheet中的第五列
            value = ParseExcelUtil.getCellData(iRow,Constants.Col_ActionValue);
            execute_Actions();
        }
    }
    private static void execute_Actions(){
        try{
            for (int i = 0;i<=method.length;i++){
                //通过遍历,判断关键字和KeyWordsaction类中的哪个方法名称一致
                if (method[i].getName().equals(keyword)){
                    //找到KeyWordsaction类中的映射方法后,通过调用invoke方法完成函数调用
                    method[i].invoke(keyWordsAction, value);
                    break;
                }
            }
        }catch (Exception e){
            //执行中出现异常,则将测试用例设定为失败状态
            Assert.fail("执行出现异常,测试用例执行失败!");
        }
    }
}

package TestScripts;
import org.apache.log4j.xml.DOMConfigurator;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.lang.reflect.Method;
import Configurations.*;
import Util.*;

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 boolean testResult;
    @BeforeMethod
    public void setUp(){
        //配置Log4j的配置文件为log4j.xml
        DOMConfigurator.configure("log4j.xml");
    }
    @Test
    public void testTestSuite()throws Exception{
        //声明一个关键动作类的实例
        keyWordsAction = new KeyWordsAction();
        //使用java的反射机制获取KeyWordsAction类中的所有方法对象
        method = keyWordsAction.getClass().getMethods();
        //定义Excel文件路径
        String excelFilePath = Constants.Path_ExcelFile;
        //设定要操作的Excel的文件路径(*设定读取Excel文件中的"SendMail" sheet为操作目标*)
        ParseExcelUtil.setExcelFile(excelFilePath);
        //读取"TestSuite"sheet中测试用例总数
        int testCasesCount = ParseExcelUtil.getRowCount(Constants.Sheet_TestSuite);
        //使用for循环执行所有标记为“y”的测试用例
        for (int testCaseNo = 1; testCaseNo<=testCasesCount; testCaseNo++){
            //读取TestSuite中每行的测试用例序号
            testCaseID = ParseExcelUtil.getCellData(Constants.Sheet_TestSuite, testCaseNo, Constants.Col_TestCaseID);
            //读取TestSuite中"是否执行"列种的值
            testCaseRunFlag = ParseExcelUtil.getCellData(Constants.Sheet_TestSuite,testCaseNo,Constants.Col_RunFlag);
            //如果"是否执行"的值为y,则执行测试用例所有步骤
            if (testCaseRunFlag.equalsIgnoreCase("y")){
                //在日志中打印测试用例开始执行
                LogUtil.startTestCases(testCaseID);
                //设定测试用例的当前结果为true,及标明测试执行成功
                testResult = true;
                //在"SendMail"sheet中,获取当前要执行测试用例的第一个步骤所在行的行号
                testStep = ParseExcelUtil.getFirstRowContainsTestCaseID(Constants.Sheet_TestSteps, testCaseID, Constants.Col_TestCaseID);
                //在"SendMail"sheet中,获取当前要执行测试用例的最后一个步骤所在行的行号
                testLastStep = ParseExcelUtil.getTestCaseLastStepRow(Constants.Sheet_TestSteps, testCaseID, testStep);
                //遍历测试用例中的所有测试步骤
                for (; testStep<testLastStep; testStep++){
                    //从"SendMail"sheet中,获取关键字和操作值,调用execute_Actions方法
                    keyword = ParseExcelUtil.getCellData(Constants.Sheet_TestSteps, testStep, Constants.Col_KeyWordAction);
                    //在日志文件中打印关键字信息
                    LogUtil.info("从Excel文件中读取到的关键字是:" + keyword);
                    locatorExpression = ParseExcelUtil.getCellData(Constants.Sheet_TestSteps, testStep,Constants.Col_LocatorExpression);
                    value = ParseExcelUtil.getCellData(Constants.Sheet_TestSteps, testStep,Constants.Col_ActionValue);
                    //在日志文件中打印操作值信息
                    LogUtil.info("从Excel文件中读取到的操作值是:" + value);
                    execute_Actions();
                    if (!testResult){
                        /*如果测试用例的任何一个测试步骤执行失败,则“TestSuite”Sheet中的当前执行的
                         *测试用例执行结果设定为“测试执行失败”
                         */
                        ParseExcelUtil.setCellData("TestSuite", testCaseNo, Constants.Col_TestSuiteTestResult, "测试执行失败");
                        //在日志中打印测试用例执行完毕
                        LogUtil.endTestCases(testCaseID);
                        /*当前测试用例出现执行失败的步骤,则整个测试用例设定为失败状态,break语句跳出当前的for循环,继续执行TestSuite的
                         *下一个测试用例
                         */
                        break;
                    }
                    if (testResult){
                        //如果测试用例的所有步骤执行成功,则会将“TestSuite”Sheet中的当前测试用例的执行结果设定为“测试执行成功”
                         ParseExcelUtil.setCellData("TestSuite", testCaseNo, Constants.Col_TestSuiteTestResult,"测试执行成功");

                    }
                }
                //在日志中打印测试用例执行完毕
                //LogUtil.endTestCases(testCaseID);
            }
        }
    }
    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){
                        //当前测试步骤执行成功,在“SendMail”Sheet中,将当前执行的测试步骤结果设定为“测试步骤执行成功”
                        ParseExcelUtil.setCellData(Constants.Sheet_TestSteps, testStep, Constants.Col_TestStepTestResult,"测试步骤执行成功");
                    }
                    break;
                }else {
                    //反之则设定为“测试步骤执行失败”
                    ParseExcelUtil.setCellData(Constants.Sheet_TestSteps,testStep,Constants.Col_TestStepTestResult,"测试步骤执行失败");
                    //测试步骤执行失败,则直接关闭浏览器,不再执行后续步骤
                    KeyWordsAction.close_browser("","");
                    break;
                }
            }
        }catch (Exception e){
            //执行中出现异常,则将测试用例设定为失败状态
            Assert.fail("执行出现异常,测试用例执行失败!");
        }
    }
}





猜你喜欢

转载自blog.csdn.net/dawei_yang000000/article/details/108019176
今日推荐