Selenium Web 自動化 - 項目實戰(三)

Selenium Web 自動化 - 項目實戰(三)

2016-08-10css

目錄前端

1 關鍵字驅動概述
2 框架更改總覽
3 框架更改詳解
  3.1 解析新增頁面目錄
  3.2 解析新增測試用例目錄
  3.3 解析自動生成代碼
  3.4 讀取用例excel數據,定位元素,並進行操做
  3.5 更改SeleniumUtil.java java

源代碼:autotestKeywordDrive.zipweb

1 關鍵字驅動概述


 返回apache

關鍵字驅動測試(Keyword-driven testing),也叫作表格驅動測試或者基於行爲詞的測試。windows

關鍵字驅動究竟是什麼樣的?數組

圖3,動做也就是關鍵字,好比你選擇了「點擊」操做,就意味着這步驟會執行一個元素點擊操做。瀏覽器

關鍵子驅動是如何實現的:cookie

問:那麼如何定義動做?網絡

答:在框架設計的時候會專門設計一個類,來實現各類「動做」的具體內容。當你在excel中讀取了一個「動做」以後,框架會自動解析這個「動做」背後的事情。在測試框架中這個類的名字叫作:SuperAction.java。

問:如何定義和解析元素定位?

答:見圖2,每一個頁面是一個excel,全部元素的定位方式和定位值都保存在裏面

問:如何用例存儲?

答:見圖3,一個excel就是一個模塊,而後這個excel文件中一個sheet就是這個模塊中的一條用例

問:Excel文件如何執行測試?

答:excel文件存儲用例,但excel只是文件,如何調用測試入口呢?其實在關鍵字驅動框架中,有一個用例生成類(TestCaseFactoryForSingle.java,TestCaseFactoryForAll.java),它能夠遍歷全部excel的全部sheet,生產一條條用例類,見圖6

關鍵字優缺點:

  • 優勢:只須要自動化測試人員封裝好相關關鍵字操做,就能夠提供給黑盒測試人員用,黑盒測試人員只須要掌握元素定位的方式以及對關鍵字框架的使用便可·條理清晰,很容易上手使用
  • 缺點:須要自動化測試人員花費大量時間提早把關鍵字框架中的操做提早封裝好對於複雜的測試需求,關鍵字框架對於操做的封裝難度較大

2 框架更改總覽


 返回

在原來的框架下更改,如下圖所示

 

圖1 關鍵子驅動與數據驅動比較

3 框架更改詳解


 返回

在原來的框架下更改,以下圖所示

3.1 解析新增頁面目錄

page: 存儲頁面元素的目錄,在此目錄下每一個頁面是一個excel,會替換原先框架的com.demo.test.pages包,如圖1所示。

 

圖2 page 元素定位excel

3.2 解析新增測試用例目錄

testcase:存儲測試用例的目錄,每一個模塊一個excel文件,每一個excel文件中的sheet是一條測試用例,會替換原先框架的com.demo.test.pageshelper包和data目錄,如圖4所示。

圖3 用例Login的Actions

測試用例excel是用於存儲測試用例步驟(如圖4所示)、步驟中涉及的動做(如圖3所示)和測試數據(如圖4所示)等內容,命名規則以下:

  • excel文件命名規則爲:「模塊名稱.xlsx」;
  • excel中第二個sheet命名規則:「001_LoginSuccessFunction」來自原框架測試代碼中的部份內容(如圖4所示),也就是省略了「頁面名稱_」:HomePage_和尾部的「_Test」部分:_Test,這兩部分省略的部分在生成代碼的時候會自動添加。

注意:測試用例excel文件sheet「001_LoginSuccessFunction」中的「動做」列(如圖4所示),這列是經過sheet「Actions」中的「動做名稱」列來賦值的:

  1. 選擇「動做」列,以下圖所示,整列已經變灰色,代表整列已經被選中。
  2. 點擊excel頂部的「數據」tab -> 數據驗證:在數據驗證-設置中選擇驗證條件爲:序列並勾選「忽略空值」和「提供下拉箭頭」,點擊來源最右邊的帶箭頭的按鈕,點擊sheet 'Actions',選擇A2到A26(鼠標左鍵先點擊A2不放,而後拖拽至A26),此時注意數據驗證框的變化:=Actions!$A$2:$A$26,點擊回車鍵。

 

圖4 用例Login的執行步驟

 

圖5 用例excel替換pagehelper類和data excel

3.3 解析自動生成代碼

自動生成代碼TestCaseFactoryForSingle.java代碼以下 

package com.demo.test.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.Assert;
import jxl.read.biff.BiffException;

/**
 * 
 * @author xy-incito-wy
 * @Description 自動生成測試代碼的工具類,生成指定模塊的用例
 *
 */
public class TestCaseFactoryForSingle {
    public static void main(String[] args) {
        //測試代碼包路徑,若是你的測試代碼目錄不同請在這裏修改
        final String caseFolder = "src/com/demo/test/testcases/";
        //源文件
        File sourceFile = null;
        //sheet的名字
        String sheetName = null;
        //功能模塊名字
        String functionName = null;
        //sheet的號碼
        int sheetNum = 0;

            try {
                @SuppressWarnings("resource")
                //從控制檯能夠輸入
                Scanner s = new Scanner(System.in); 
                System.out.println("請輸入模塊名稱(不要按回車鍵,輸入完成以後請再按回車鍵):"); 
                functionName = s.nextLine();// 輸入模塊名字

                functionName = functionName.replaceFirst(
                        functionName.substring(0, 1),
                        functionName.substring(0, 1).toLowerCase());
                // 若是包名不存在,就新建
                File functionPackage = new File(caseFolder + "/" + functionName);
                if (functionPackage.exists()) {
                    System.out.println(functionName + "包已經存在,自動跳過!");
                    System.out.println("正在生成用例到" + functionName + "包下,請稍等...");
                } else {
                    functionPackage.mkdir();
                    System.out.println(functionName + "包已建立!");
                    System.out.println("正在生成用例到" + functionName + "包下,請稍等...");
                }

                for (int j = 0; j < getSheetNum(getExcelRelativePath(functionName)); j++) { // 根據傳入的模塊文件路徑得到模塊中sheet數量 也就是用例個數

                    if (j == getSheetNum(getExcelRelativePath(functionName)) - 1) {
                        //若是隻有一個sheet的時候(只有Value的狀況下),跳出循環不進行自動生成代碼操做,由於沒有能夠生成的。
                        break;
                    }
                    try {
                        sheetName = getSheetName(j + 1, getExcelRelativePath(functionName)); // 取得sheetName,因爲第一個sheet是values,因此從j+1開始
                                                                                
                        sheetNum = getSheetNum(getExcelRelativePath(functionName));
                    } catch (BiffException e1) {
                        e1.printStackTrace();
                    }
                    sourceFile = new File(caseFolder
                            + functionName.toLowerCase()
                            + File.separator
                            + functionName.replaceFirst(functionName.substring(
                                    0, 1), functionName.substring(0, 1)
                                    .toUpperCase()) + "Page_" + sheetName
                            + "_Test.java");// 建立測試用例源碼,指定存放路徑
                    FileWriter writer = new FileWriter(sourceFile);

                    // 生成測試用例代碼的頭文件
                    writer.write("package com.demo.test.testcases."
                            + functionName
                            + "; \n"
                            + "import org.testng.annotations.Test; \n"
                            + "import com.demo.test.base.BaseParpare; \n "
                            + "import com.demo.test.utils.SuperAction; \n"
                            + "public class "
                            + functionName.replaceFirst(functionName.substring(
                                    0, 1), functionName.substring(0, 1)
                                    .toUpperCase()) + "Page_" + sheetName
                            + "_Test extends BaseParpare{ \n");

                    // @Test的主體部分,也就是測試用例的方法
                    String firstLetter = sheetName.substring(
                            sheetName.indexOf("_") + 1).substring(0, 1);
                    String others = sheetName.substring(
                            sheetName.indexOf("_") + 1).substring(1);
                    String function = firstLetter.toLowerCase() + others;
                    writer.write("@Test \n"
                            + " public void"
                            + " "
                            + function
                            + "() { \n"
                            + "SuperAction.parseExcel(\""
                            + functionName.replaceFirst(functionName.substring(
                                    0, 1), functionName.substring(0, 1)
                                    .toUpperCase()) + "\",\"" + sheetName
                            + "\",seleniumUtil);\n" + " }\n");

                    // 代碼結尾大括號
                    writer.write("}");
                    writer.close();
                }
            } catch (IOException e) {
                Assert.fail("IO異常", e);
            }
            System.out.println("模塊[" + functionName + "] 的用例已經生成完畢,共計:"
                    + (sheetNum - 1) + "條,請到" + caseFolder
                    + functionName.toLowerCase() + "路徑下查閱!");
    

    }


    /**
     * 得到excel的相對路徑
     * 
     * @param 循環模塊名稱的角標
     * @return 獲得對應index的模塊名字
     */
    public static String getExcelRelativePath(String functionName) {
        String dir = "res/testcase";
        String path = "";
        // get file list where the path has
        File file = new File(dir+File.separator+functionName+".xlsx");
        // get the folder list
        path = file.getPath();
        return path;
    }

    /**
     * 得到當前excel的sheet數量 - 每一個模塊的用例數
     * 
     * @param filePath
     *            文件路徑
     * @return 得到excel的sheet數量
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static int getSheetNum(String filePath)
            throws FileNotFoundException, IOException {
        int casesNum = 0;
        XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(
                filePath)));
        casesNum = workbook.getNumberOfSheets();

        return casesNum;
    }

    /**
     * 
     * @param sheetIndex
     *            sheet的位置
     * @param filePath
     *            excel文件路徑相對的
     * @return 返回sheet的名字
     * @throws BiffException
     * @throws IOException
     */
    public static String getSheetName(int sheetIndex, String filePath)
            throws BiffException, IOException {
        String casesName = "";
        XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(filePath));
        casesName = workbook.getSheetName(sheetIndex);

        return casesName;

    }

}
View Code

TestCaseFactoryForSingle.java這個類,這個類主要是用於生成指定模塊的測試用例,這個類有一個main方法,當你執行以後,會提示你輸入要生成測試代碼的模塊。這裏的模塊的名字就是testcase目錄下的excel文件名字(不包含後綴),而後回車,
此時回到src/com/demo/test/testcases/login包下查看,一條用例生成了 LoginPage_001_LoginSuccessFunction_Test.java,如圖5所示.

在pom.xml中,添加jar依賴

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.10-FINAL</version>
        </dependency>
View Code

 

圖6 自動生成代碼

3.4 讀取用例excel數據,定位元素,並進行操做

SuperAction.java代碼以下:

package com.demo.test.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.testng.Assert;
/**
 * 
 * @Description 把Selenium操做的變成關鍵字操做
 *
 */
public class SuperAction {
    public static Logger logger = Logger.getLogger(SuperAction.class.getName());
    //static  String pageFilePath = "res/page/PageElements.xlsx";
    static String pageFileDir = "res/page/";
    public static Alert a = null;
    /**
     * 
     * @param locateWay 定位方式
     * @param locateValue 定位的方式的具體值
     * @return 定位的方式(By)
     */
    public static By getLocateWay(String locateWay,String locateValue){
         By elementLocator=null;
             if(locateWay.equalsIgnoreCase("xpath")){
                 elementLocator=By.xpath(locateValue);
             }
             else if(locateWay.equalsIgnoreCase("className")){
                 elementLocator=By.className(locateValue);
             }
             else if(locateWay.equalsIgnoreCase("id")){
                 elementLocator=By.id(locateValue);
             }
             else    if(locateWay.equalsIgnoreCase("linktext")){
                 elementLocator=By.linkText(locateValue);
             }
             else    if(locateWay.equalsIgnoreCase("name")){
                 elementLocator=By.name(locateValue);
             }
             else    if(locateWay.equalsIgnoreCase("css")){
                 elementLocator=By.cssSelector(locateValue);
             }
             else    if(locateWay.equalsIgnoreCase("tagname")){
                 elementLocator=By.tagName(locateValue);
             }
             else{
                 Assert.fail("你選擇的定位方式:["+locateWay+"] 不被支持!");
             }
             return elementLocator;
         }
    

    /**
     * 
     * @param sheet - 測試用例表中的sheet
     * @param rowIndex - 測試用例表中的行index
     * @param locateColumnIndex - 測試用例表中的定位列的index
     * @return 從page表中 返回定位方式和定位值
     * @Description 根據testcase中的元素定位列,去取得page頁中的 定位方式和定位值
     */
    public static String[] getPageElementLocator(Sheet sheet,int rowIndex,int locateColumnIndex,String pageName){

            XSSFWorkbook pageBook = null;
            //定位方式
            String elementLocatorWay = null;
            //定位值
            String elementLocatorValue = null;
            //sheet表
            Sheet pageSheet = null;
            //page excel路徑
            String pageFilePath = pageFileDir+pageName+".xlsx";
            //獲取定位列的值
            String locator = sheet.getRow(rowIndex).getCell(locateColumnIndex).getStringCellValue();
            //用.分割開元素定位值
            String locatorSplit[] = locator.split("\\.");
        try {
            pageBook = new XSSFWorkbook(new FileInputStream(new File(pageFilePath)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 

          pageSheet =  pageBook.getSheetAt(0); //取得第一個sheet
         int pageRowNum =  pageSheet.getPhysicalNumberOfRows();//得到這個sheet的實際有效行數
         for (int j = 0; j < pageRowNum; j++) {
             //若是獲取到的別名和指定的別名相同,就存儲當前行的定位值和定位方式
            if(pageSheet.getRow(j).getCell(0).getStringCellValue().equalsIgnoreCase(locatorSplit[1])){
                 elementLocatorWay = pageSheet.getRow(j).getCell(1).getStringCellValue();
                 elementLocatorValue = pageSheet.getRow(j).getCell(2).getStringCellValue();
                break;
            }
        }
        return new String[]{elementLocatorWay,elementLocatorValue};
    
    }
    /**
     * @param founction
     *            excel文件的名字
     * @param caseName
     *            excel中sheet的名字
     * @param seleniumUtil
     *            引用seleniumUtil
     * @Description 讀取excel中每一個sheet的操做步驟,進而生成測試用例
     * */
    public static void parseExcel(String founction, String caseName, SeleniumUtil seleniumUtil) {
        FileInputStream filePath = null;
        XSSFWorkbook workbook = null;
        String locateSplit[]  = null;//頁面sheet中的定位方式和定位值拆解
        String locator = null;//用例頁面的定位列
        String file = "res/testcase/" + founction + ".xlsx";
        try {
            filePath = new FileInputStream(file);// 讀取功能模塊
        } catch (FileNotFoundException e) {
            logger.error("文件:" + file + "不存在");
            Assert.fail("文件:" + file + "不存在");
        }
        try {
            workbook = new XSSFWorkbook(filePath);
        } catch (IOException e) {
            logger.error("IO異常");
            Assert.fail("IO異常");
        }
        /**取得指定的case名字*/
        Sheet sheet = workbook.getSheet(caseName);
        /**得到的實際行數*/
        int rows = sheet.getPhysicalNumberOfRows(); 
        /** excel中的測試數據*/
        String testData = null;
        //獲取首行的單元格數
        int cellsNumInOneRow = sheet.getRow(0).getPhysicalNumberOfCells();
        //聲明一個數組存儲列值的角標
        String column[] = new String[cellsNumInOneRow];
        //聲明一個迭代器
        Iterator<Cell> cell = sheet.getRow(0).iterator();
        int ii =0;
        while(cell.hasNext()){
            column[ii]= String.valueOf(cell.next()); 
            ii++;
        }
        //定義動做列的角標
        int actionColumnIndex =0;
        //定義元素定位列的角標
        int locateColumnIndex = 0;
        //定義測試數據列的角標
        int testDataColumnIndex = 0;
        //動態獲取這幾個關鍵列所在位置
         for (int i = 0; i < column.length; i++) {
             if(column[i].equals("動做")){
                 actionColumnIndex = i;
             }
             if(column[i].equals("元素定位")){
                 locateColumnIndex = i;
             }
             if(column[i].equals("測試數據")){
                 testDataColumnIndex = i;
             }
            
        }

            // 循環每行的操做,根據switch來判斷每行的操做是什麼,而後轉換成具體的代碼,從第二行開始循環,由於第一行是列的說明數據。    
        for (int i = 1; i < rows; i++) {
            logger.info("正在解析excel:["+founction+".xlsx]中的sheet(用例):["+caseName+"]的第"+i+"行步驟...");
            String action = sheet.getRow(i).getCell(actionColumnIndex).getStringCellValue();
            Row row = sheet.getRow(i);
            if (row != null) {
                switch (action) {
                case "打開連接":
                    testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();
                    seleniumUtil.get(testData);
                    break;
                    
                case "導航連接":
                    testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();
                    seleniumUtil.get(testData);
                    break;
                    
                case "輸入":
                    //先設置Cell的類型,而後就能夠把純數字做爲String類型讀進來了
                    sheet.getRow(i).getCell(testDataColumnIndex).setCellType(Cell.CELL_TYPE_STRING);
                    testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue(); //測試數據
                    locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的元素定位
                    //locator.split("\\.")[0]分離出頁面名稱,好比HomePage.個人單據,提取出HomePage
                    locateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]); //找到定位方式、定位值
                    seleniumUtil.type(getLocateWay(locateSplit[0], locateSplit[1]), testData);
                    break;
                    
                case "點擊":
                    locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位
                    //locator.split("\\.")[0]分離出頁面名稱,好比HomePage.個人單據,提取出HomePage
                    locateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);
                    seleniumUtil.click(getLocateWay(locateSplit[0], locateSplit[1]));
                    break;
                    
                case "暫停":
                    //先設置Cell的類型,而後就能夠把純數字做爲String類型讀進來了
                    sheet.getRow(i).getCell(testDataColumnIndex).setCellType(Cell.CELL_TYPE_STRING);
                    testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();
                    seleniumUtil.pause(Integer.parseInt(testData));
                    break;
                    
                case "等待元素":
                    //先設置Cell的類型,而後就能夠把純數字做爲String類型讀進來了
                    sheet.getRow(i).getCell(testDataColumnIndex).setCellType(Cell.CELL_TYPE_STRING);
                    testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();
                    locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位
                    //locator.split("\\.")[0]分離出頁面名稱,好比HomePage.個人單據,提取出HomePage
                    locateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);
                    seleniumUtil.waitForElementToLoad(Integer.parseInt(testData), getLocateWay(locateSplit[0], locateSplit[1]));
                    break;
                    
                case "查找元素(嘗試3次)":
                    //先設置Cell的類型,而後就能夠把純數字做爲String類型讀進來了
                    sheet.getRow(i).getCell(testDataColumnIndex).setCellType(Cell.CELL_TYPE_STRING);
                    testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();
                    locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位
                    //locator.split("\\.")[0]分離出頁面名稱,好比HomePage.個人單據,提取出HomePage
                    locateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);
                    seleniumUtil.FindElementUtil3TimesTry(Integer.parseInt(testData), getLocateWay(locateSplit[0], locateSplit[1]));
                    break;
                    
                case "清除":
                    locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位
                    //locator.split("\\.")[0]分離出頁面名稱,好比HomePage.個人單據,提取出HomePage
                    locateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);
                    seleniumUtil.clear(getLocateWay(locateSplit[0], locateSplit[1]));
                    break;
                    
                case "進入iFrame":
                    locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位
                    //locator.split("\\.")[0]分離出頁面名稱,好比HomePage.個人單據,提取出HomePage
                    locateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);
                    seleniumUtil.switchFrame(getLocateWay(locateSplit[0], locateSplit[1]));
                    break;
                    
                case "跳出iFrame":
                    seleniumUtil.outFrame();
                    break;
                    
                case "選擇下拉列表 - Text":
                    //先設置Cell的類型,而後就能夠把純數字做爲String類型讀進來了
                    sheet.getRow(i).getCell(testDataColumnIndex).setCellType(Cell.CELL_TYPE_STRING);
                    testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();
                    locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位
                    //locator.split("\\.")[0]分離出頁面名稱,好比HomePage.個人單據,提取出HomePage
                    locateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);
                    seleniumUtil.selectByText(getLocateWay(locateSplit[0], locateSplit[1]), testData);
                    break;
                    
                case "選擇下拉列表 - Index":
                    //先設置Cell的類型,而後就能夠把純數字做爲String類型讀進來了
                    sheet.getRow(i).getCell(testDataColumnIndex).setCellType(Cell.CELL_TYPE_STRING);
                    testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();
                    locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位
                    //locator.split("\\.")[0]分離出頁面名稱,好比HomePage.個人單據,提取出HomePage
                    locateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);
                    seleniumUtil.selectByIndex(getLocateWay(locateSplit[0], locateSplit[1]), Integer.parseInt(testData));
                    break;
                    
                case "選擇下拉列表 - Value":
                    //先設置Cell的類型,而後就能夠把純數字做爲String類型讀進來了
                    sheet.getRow(i).getCell(testDataColumnIndex).setCellType(Cell.CELL_TYPE_STRING);
                    testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();
                    locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位
                    //locator.split("\\.")[0]分離出頁面名稱,好比HomePage.個人單據,提取出HomePage
                    locateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);
                    seleniumUtil.selectByValue(getLocateWay(locateSplit[0], locateSplit[1]),testData );
                    break;                        
                    
                case "檢查文本 - 屬性":
                    testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();
                    locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位
                    //locator.split("\\.")[0]分離出頁面名稱,好比HomePage.個人單據,提取出HomePage
                    locateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);
                    String[] Datas = testData.split(",");
                    seleniumUtil.isTextCorrect(seleniumUtil.getAttributeText(getLocateWay(locateSplit[0], locateSplit[1]), Datas[0]),Datas[1]);
                    break;
                    
                case "得到網頁標題":
                    testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();
                    seleniumUtil.isTextCorrect(seleniumUtil.getTitle(),testData);
                    break;
                    
            
                case "頁面的URL是否正確":
                    testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();
                    seleniumUtil.isTextCorrect(seleniumUtil.getPageURL(), testData);
                    break;
                    
                case "檢查文本":
                    testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();
                    locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位
                    //locator.split("\\.")[0]分離出頁面名稱,好比HomePage.個人單據,提取出HomePage
                    locateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);
                    seleniumUtil.isTextCorrect(seleniumUtil.getText(getLocateWay(locateSplit[0], locateSplit[1])), testData);
                    break;
                    
                case "進入Tab":
                    //須要改進,第二個窗口的driver問題
                    locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位
                    //locator.split("\\.")[0]分離出頁面名稱,好比HomePage.個人單據,提取出HomePage
                    locateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);
                    seleniumUtil.switchNewWindow(getLocateWay(locateSplit[0], locateSplit[1]));
                    break;
                    
                case "跳出Tab":
                    seleniumUtil.backToOriginalWindow();
                    break;
                    
                case "接受alert彈窗":
                    //先設置Cell的類型,而後就能夠把純數字做爲String類型讀進來了
                    sheet.getRow(i).getCell(testDataColumnIndex).setCellType(Cell.CELL_TYPE_STRING);
                    testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();
                    a = seleniumUtil.switchToPromptedAlertAfterWait(Long.parseLong(testData));
                    a.accept();
                    break;
                    
                case "取消alert彈窗":
                    //先設置Cell的類型,而後就能夠把純數字做爲String類型讀進來了
                    sheet.getRow(i).getCell(testDataColumnIndex).setCellType(Cell.CELL_TYPE_STRING);
                    testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();
                    a = seleniumUtil.switchToPromptedAlertAfterWait(Long.parseLong(testData));
                    a.dismiss();
                    break;    
                    
                case "執行JS點擊":
                    locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位
                    //locator.split("\\.")[0]分離出頁面名稱,好比HomePage.個人單據,提取出HomePage
                    locateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);
                    seleniumUtil.executeJS("arguments[0].click();", seleniumUtil.findElementBy(getLocateWay(locateSplit[0], locateSplit[1])));
                    break;    
                    
                case "刷新頁面":
                    seleniumUtil.refresh();
                    break;    
                    
                case "前進頁面":
                    seleniumUtil.back();
                    break;
                    
                case "後退頁面":
                    seleniumUtil.forward();
                    break;
                    
                case "上傳文件":
                    testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();
                    String uploadValues[] = testData.split(",");
                    seleniumUtil.handleUpload(uploadValues[0], new File(uploadValues[1]));
                    break;
                    
                case "元素被啓用":
                    locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位
                    //locator.split("\\.")[0]分離出頁面名稱,好比HomePage.個人單據,提取出HomePage
                    locateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);
                    if(seleniumUtil.isEnabled(getLocateWay(locateSplit[0], locateSplit[1]))){
                        logger.info(getLocateWay(locateSplit[0], locateSplit[1])+"元素被啓用");
                    }else{
                        Assert.fail(getLocateWay(locateSplit[0], locateSplit[1])+":沒有被啓用");
                    }
                    break;
                    
                case "元素未啓用":
                    locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位
                    //locator.split("\\.")[0]分離出頁面名稱,好比HomePage.個人單據,提取出HomePage
                    locateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);
                    if(seleniumUtil.isEnabled(getLocateWay(locateSplit[0], locateSplit[1]))){
                        Assert.fail(getLocateWay(locateSplit[0], locateSplit[1])+"元素被啓用");
                    }else{
                        logger.info(getLocateWay(locateSplit[0], locateSplit[1])+":沒有被啓用");
                    }
                    break;
                    
                case "驗證首頁菜單欄文本":
                    locator = sheet.getRow(i).getCell(locateColumnIndex).getStringCellValue();//獲取步驟中的定位
                    //locator.split("\\.")[0]分離出頁面名稱,好比HomePage.個人單據,提取出HomePage
                    locateSplit = getPageElementLocator(sheet, i, locateColumnIndex,locator.split("\\.")[0]);
                    testData = sheet.getRow(i).getCell(testDataColumnIndex).getStringCellValue();
                    String menus[] = testData.split(",");
                    for (int i1 = 0; i1 < menus.length; i1++) {
                        seleniumUtil.isTextCorrect(seleniumUtil.findElementsBy(getLocateWay(locateSplit[0], locateSplit[1])).get(i1).getText().trim().toLowerCase(), menus[i1].toLowerCase());
                    }
                    
                    break;
                    
                    
                    default:
                        logger.error("你輸入的操做:["+action+"]不被支持,請自行添加");
                        Assert.fail("你輸入的操做:["+action+"]不被支持,請自行添加");
                    
                }
            }
        }
    }

}
View Code

3.5 更改SeleniumUtil.java

SeleniumUtil.java代碼以下:

package com.demo.test.utils;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
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 org.testng.ITestContext;
import org.testng.ITestResult;


/**
 * @Description 包裝全部selenium的操做以及通用方法,簡化用例中代碼量
 * */
public class SeleniumUtil {
    /** 使用Log4j,第一步就是獲取日誌記錄器,這個記錄器將負責控制日誌信息 */
    public static Logger logger = Logger.getLogger(SeleniumUtil.class.getName());
    public ITestResult it = null;
    public WebDriver driver = null;
    public WebDriver window = null;
    public String current_handles="";



    /***
     * 啓動瀏覽器並打開頁面
     * */
    public void launchBrowser(String browserName, ITestContext context,String webUrl,int timeOut) {
        SelectBrowser select = new SelectBrowser();
        driver = select.selectExplorerByName(browserName, context);
        try {
            maxWindow(browserName);
            waitForPageLoading(timeOut);
            get(webUrl);
        } catch (TimeoutException e) {
            logger.warn("注意:頁面沒有徹底加載出來,刷新重試!!");
            refresh();
             JavascriptExecutor js = (JavascriptExecutor)driver;
            String status= (String)js.executeScript("return document.readyState");
        
            
            logger.info("打印狀態:"+status);
        }

    }

    
    /**
     * 最大化瀏覽器操做
     * */
    public void maxWindow(String browserName) {
        logger.info("最大化瀏覽器:" + browserName);
        driver.manage().window().maximize();
    }

    /**
     * 設定瀏覽器窗口大小: 設置瀏覽器窗口的大小有下面兩個比較常見的用途:<br>
     * 一、在統一的瀏覽器大小下運行用例,能夠比較容易的跟一些基於圖像比對的工具進行結合
     * ,提高測試的靈活性及廣泛適用性。好比能夠跟sikuli結合,使用sikuli操做flash;<br>
     * 二、在不一樣的瀏覽器大小下訪問測試站點,對測試頁面截圖並保存,而後觀察或使用圖像比對工具對被測頁面的前端樣式進行評測。
     * 好比能夠將瀏覽器設置成移動端大小(320x480),而後訪問移動站點,對其樣式進行評估;<br>
     * */
    public void setBrowserSize(int width, int height) {
        driver.manage().window().setSize(new Dimension(width, height));
    }

    /**
     * 包裝查找元素的方法 element
     * */
    public WebElement findElementBy(By by) {
        return driver.findElement(by);
    }

    /**
     * 包裝查找元素的方法 elements
     * */
    public List<WebElement> findElementsBy(By by) {
        return driver.findElements(by);
    }
    
    /**導航連接到url*/
    public void navigateTargetUrl(String url){
        driver.navigate().to(url);
        logger.info("導航到:"+url);
    }

    /**
     * 包裝點擊操做- By
     * */
    public void click(By byElement) {

        try {
            clickTheClickable(byElement, System.currentTimeMillis(), 2500);
        } catch (StaleElementReferenceException e) {
            logger.error("The element you clicked:[" + byElement + "] is no longer exist!");
            Assert.fail("The element you clicked:[" + byElement + "] is no longer exist!");
        } catch (Exception e) {
            logger.error("Failed to click element [" + byElement + "]");
            Assert.fail("Failed to click element [" + byElement + "]",e);
        }
        logger.info("點擊元素 [" + byElement + "]");
    }
    
    public boolean isEnabled(By by){
        return driver.findElement(by).isEnabled();
    }
    
    /**提交*/
    public void submit(WebElement w){
        try{
        w.submit();
        
        }catch(Exception e){
            logger.error("在元素:"+w+"作的提交操做失敗");
            Assert.fail("在元素:"+w+"作的提交操做失敗");
        }
        logger.info("在元素:"+w+"作了提交操做");
    }

    /**
     * 包裝點擊操做 -webelment
     * */
    public void click(WebElement element) {

        try {
            element.click();
        } catch (StaleElementReferenceException e) {
            logger.error("The element you clicked:[" + element.toString() + "] is no longer exist!");
            Assert.fail("The element you clicked:[" + element.toString() + "] is no longer exist!");
        } catch (Exception e) {
            logger.error("Failed to click element [" + element.toString() + "]");
            Assert.fail("Failed to click element [" + element.toString() + "]",e);
        }
        logger.info("點擊元素 [" + element.toString() + "]");
    }

    /** 不能點擊時候重試點擊操做 */
    public void clickTheClickable(By byElement, long startTime, int timeOut) throws Exception {
        try {
            findElementBy(byElement).click();
        } catch (Exception e) {
            if (System.currentTimeMillis() - startTime > timeOut) {
                logger.warn(byElement+ " is unclickable");
                throw new Exception(e);
            } else {
                Thread.sleep(500);
                logger.warn(byElement + " is unclickable, try again");
                clickTheClickable(byElement, startTime, timeOut);
            }
        }
    }

    /**
     * 得到頁面的標題
     * */
    public String getTitle() {
        return driver.getTitle();
    }

    /**
     * 得到元素的文本
     * */
    public String getText(By elementLocator) {
        return driver.findElement(elementLocator).getText().trim();
    }

    /**
     * 得到元素 屬性的文本
     * */
    public String getAttributeText(By elementLocator, String attribute) {
        return driver.findElement(elementLocator).getAttribute(attribute).trim();
    }

    /**
     * 包裝清除操做
     * */
    public void clear(By byElement) {
        try {
            findElementBy(byElement).clear();
        } catch (Exception e) {
            logger.error("清除元素 [" + byElement + "] 上的內容失敗!");
        }
        logger.info("清除元素 [" + byElement  + "]上的內容");
    }

    /**
     * 向輸入框輸入內容
     * */
    public void type(By byElement, String key) {
        try {
            findElementBy(byElement).sendKeys(key);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("輸入 [" + key + "] 到 元素[" + byElement + "]失敗");
            Assert.fail("輸入 [" + key + "] 到 元素[" + byElement + "]失敗",e);
        }
        logger.info("輸入:[" + key + "] 到 [" + byElement + "]");
    }

    /**
     * 模擬鍵盤操做的,好比Ctrl+A,Ctrl+C等 參數詳解:<br>
     * 一、WebElement element - 要被操做的元素 <br>
     * 二、Keys key- 鍵盤上的功能鍵 好比ctrl ,alt等 <br>
     * 三、String keyword - 鍵盤上的字母
     * */
    public void pressKeysOnKeyboard(WebElement element, Keys key, String keyword) {

        element.sendKeys(Keys.chord(key, keyword));
    }

    /**
     * 在給定的時間內去查找元素,若是沒找到則超時,拋出異常
     * */
    public void waitForElementToLoad(int timeOut, final By By) {
        logger.info("開始查找元素[" + 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) {
            logger.error("超時!! " + timeOut + " 秒以後還沒找到元素 [" + By + "]");
            Assert.fail("超時!! " + timeOut + " 秒以後還沒找到元素 [" + By + "]");

        }
        logger.info("找到了元素 [" + By + "]");
    }

    /**
     * 在給定的時間內查詢元素,共嘗試三次,若是第三次仍是找不到就報錯,這就多是網頁性能問題了,響應速度不夠
     * */
    public void FindElementUtil3TimesTry(int timeOut, final By By ) {
     int find=0;
        int notFindTimes = 0;
        boolean flag = true;
        while(flag){
            if(notFindTimes==3){
                logger.error("嘗試了3次查找都未查找到元素:"+By+"請檢查是否是網絡或者網站性能問題(響應速度不夠)");
                Assert.fail("嘗試了3次查找都未查找到元素:"+By+"請檢查是否是網絡或者網站性能問題(響應速度不夠)");
            }
        logger.info("開始第"+(notFindTimes+1)+"次查找元素[" + By + "]");
        try {
            (new WebDriverWait(driver, timeOut)).until(new ExpectedCondition<Boolean>() {

                public Boolean apply(WebDriver driver) {
                    WebElement element = driver.findElement(By);
                    return element.isDisplayed();
                }
            });
            find++;
        } catch (TimeoutException e) {
            logger.warn("超時!! " + timeOut + " 秒以後還沒找到元素 [" + By + "],這是第"+(notFindTimes+1)+"次查找!");
            notFindTimes++;
            if(notFindTimes<3){
            refresh();
            }
        }
        
        
        if(notFindTimes>0&find!=1){
            flag = true;
        }else{
            flag = false;
        }
        

        }
    
        logger.info("找到了元素 [" + By + "]");
    }

    /**
     * 判斷文本是否是和需求要求的文本一致
     * **/
    public void isTextCorrect(String actual, String expected) {
        try {
            Assert.assertEquals(actual, expected);
        } catch (AssertionError e) {
            logger.error("指望的文字是 [" + expected + "] 可是找到了 [" + actual + "]");
            Assert.fail("指望的文字是 [" + expected + "] 可是找到了 [" + actual + "]");

        }
        logger.info("找到了指望的文字: [" + expected + "]");

    }

    /**
     * 判斷編輯框是否是可編輯
     * */
    public void isInputEdit(WebElement element) {

    }

    /**
     * 等待alert出現
     * */
    public Alert switchToPromptedAlertAfterWait(long waitMillisecondsForAlert) throws NoAlertPresentException {
        final int ONE_ROUND_WAIT = 200;
        NoAlertPresentException lastException = null;

        long endTime = System.currentTimeMillis() + waitMillisecondsForAlert;

        for (long i = 0; i < waitMillisecondsForAlert; i += ONE_ROUND_WAIT) {

            try {
                Alert alert = driver.switchTo().alert();
                return alert;
            } catch (NoAlertPresentException e) {
                lastException = e;
            }
                try {
                    Thread.sleep(ONE_ROUND_WAIT);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            if (System.currentTimeMillis() > endTime) {
                break;
            }
        }
        throw lastException;
    }

    /**
     * 暫停當前用例的執行,暫停的時間爲:sleepTime
     * */
    public void pause(int sleepTime) {
        if (sleepTime <= 0) {
            return;
        }
        try {
            TimeUnit.SECONDS.sleep(sleepTime); 
            logger.info("暫停:"+sleepTime+"秒");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
    }

    /**
     * 退出
     * */
    public void quit() {
        driver.quit();
    }

    /**
     * 切換frame - 根據String類型(frame名字)
     * */
    public void inFrame(String frameId) {
        driver.switchTo().frame(frameId);
    }

    /**
     * 切換frame - 根據frame在當前頁面中的順序來定位
     * */
    public void inFrame(int frameNum) {
        driver.switchTo().frame(frameNum);
    }

    /**
     * 切換frame - 根據頁面元素定位
     * */
    public void switchFrame(By byElement) {
        try {
            logger.info("Start switching to frame [" + byElement + "]");
            driver.switchTo().frame(findElementBy(byElement));
        } catch (Exception e) {
            logger.info("Switch to frame [" + byElement + "] failed");
            Assert.fail("Switch to frame [" + byElement + "] failed");
        }
        logger.info("Switch to frame [" + byElement + "] successed");
    }

    /**
     * 選擇下拉選項 -根據value
     * */
    public void selectByValue(By by, String value) {
        Select s = new Select(driver.findElement(by));
        s.selectByValue(value);
    }

    /**
     * 選擇下拉選項 -根據index角標
     * */
    public void selectByIndex(By by, int index) {
        Select s = new Select(driver.findElement(by));
        s.selectByIndex(index);
    }

    /** 檢查checkbox是否是勾選 */
    public boolean doesCheckboxSelected(By elementLocator) {
        if (findElementBy(elementLocator).isSelected() == true) {
            logger.info("CheckBox: " + getLocatorByElement(findElementBy(elementLocator), ">") + " 被勾選");
            return true;
        } else
            logger.info("CheckBox: " + getLocatorByElement(findElementBy(elementLocator), ">") + " 沒有被勾選");
        return false;

    }

    /**
     * 選擇下拉選項 -根據文本內容
     * */
    public void selectByText(By by, String text) {
        Select s = new Select(driver.findElement(by));
        s.selectByVisibleText(text);
        logger.info("你選擇了:"+text);
    }
    
    /**
     * 得到當前select選擇的值
     * */
    public String getCurrentSelectValue(By by){
        
        Select s = new Select(driver.findElement(by));
        WebElement e =  s.getFirstSelectedOption();
            return e.getText().trim();
    }
    
    /**
     * 獲取下拉列表的全部選項
     * @param By:By元素對象
     * @return 返回全部下拉列表中的選項,如option1,option2,……
     * */
    public String getSelectOption(By by) {
        String value = null;
        Select s = new Select(driver.findElement(by));
        List<WebElement> options = s.getOptions();
        for(int i = 0 ; i< options.size() ; i++){
            value = value + "," + options.get(i).getText();        
        }        
        return value.replace("null,","");
    }

    /**
     * 執行JavaScript 方法
     * */
    public void executeJS(String js) {
        ((JavascriptExecutor) driver).executeScript(js);
        logger.info("執行JavaScript語句:[" + js + "]");
    }
    
    /**
     * 得到輸入框的值 這個方法 是針對某些input輸入框 沒有value屬性,可是又想取得input的 值得方法
     * */
    public String getInputValue(String chose,String choseValue) {
        String value = null;
        switch(chose.toLowerCase()){
        case "name":
             String jsName = "return document.getElementsByName('"+choseValue+"')[0].value;"; //把JS執行的值 返回出去
             value = (String)((JavascriptExecutor) driver).executeScript(jsName);
             break;
            
        case "id":
             String jsId = "return document.getElementById('"+choseValue+"').value;"; //把JS執行的值 返回出去
             value = (String)((JavascriptExecutor) driver).executeScript(jsId);
             break;
        
            default:
                logger.error("未定義的chose:"+chose);
                Assert.fail("未定義的chose:"+chose);
        
        }
        return value;

    }

    /**
     * 執行JavaScript 方法和對象
     * 用法:seleniumUtil.executeJS("arguments[0].click();", seleniumUtil.findElementBy(MyOrdersPage.MOP_TAB_ORDERCLOSE));
     * */
    public void executeJS(String js, Object... args) {
        ((JavascriptExecutor) driver).executeScript(js, args);
        logger.info("執行JavaScript語句:[" + js + "]");
    }

    /**
     * get方法包裝
     * */
    public void get(String url) {
        driver.get(url);
        logger.info("打開測試頁面:[" + url + "]");
    }

    /**
     * close方法包裝
     * */
    public void close() {
        driver.close();
    }

    /**
     * 刷新方法包裝
     * */
    public void refresh() {
        driver.navigate().refresh();
        logger.info("頁面刷新成功!");
    }

    /**
     * 後退方法包裝
     * */
    public void back() {
        driver.navigate().back();
    }

    /**
     * 前進方法包裝
     * */
    public void forward() {
        driver.navigate().forward();
    }

    /**
     * 包裝selenium模擬鼠標操做 - 鼠標移動到指定元素
     * */
    public void mouseMoveToElement(By by) {
        Actions builder = new Actions(driver);
        Actions mouse = builder.moveToElement(driver.findElement(by));
        mouse.perform();
    }

    /**
     * 包裝selenium模擬鼠標操做 - 鼠標移動到指定元素
     * */
    public void mouseMoveToElement(WebElement element) {
        Actions builder = new Actions(driver);
        Actions mouse = builder.moveToElement(element);
        mouse.perform();
    }
    
    /**
     * 包裝selenium模擬鼠標操做 - 鼠標右擊
     * */
    public void mouseRightClick(By element) {
        Actions builder = new Actions(driver);
        Actions mouse = builder.contextClick(findElementBy(element));
        mouse.perform();
    }

    /**
     * 添加cookies,作自動登錄的必要方法
     * */
    public void addCookies(int sleepTime) {
        pause(sleepTime);
        Set<Cookie> cookies = driver.manage().getCookies();
        for (Cookie c : cookies) {
            System.out.println(c.getName() + "->" + c.getValue());
            if (c.getName().equals("logisticSessionid")) {
                Cookie cook = new Cookie(c.getName(), c.getValue());
                driver.manage().addCookie(cook);
                System.out.println(c.getName() + "->" + c.getValue());
                System.out.println("添加成功");
            } else {
                System.out.println("沒有找到logisticSessionid");
            }

        }

    }

    /** 得到CSS value */
    public String getCSSValue(WebElement e, String key) {

        return e.getCssValue(key);
    }

    /** 使用testng的assetTrue方法 */
    public void assertTrue(WebElement e, String content) {
        String str = e.getText();
        Assert.assertTrue(str.contains(content), "字符串數組中不含有:" + content);

    }

    /** 跳出frame */
    public void outFrame() {

        driver.switchTo().defaultContent();
    }

    // webdriver中能夠設置不少的超時時間
    /** implicitlyWait。識別對象時的超時時間。過了這個時間若是對象還沒找到的話就會拋出NoSuchElement異常 */
    public void implicitlyWait(int timeOut) {
        driver.manage().timeouts().implicitlyWait(timeOut, TimeUnit.SECONDS);
    }

    /** setScriptTimeout。異步腳本的超時時間。webdriver能夠異步執行腳本,這個是設置異步執行腳本腳本返回結果的超時時間 */
    public void setScriptTimeout(int timeOut) {
        driver.manage().timeouts().setScriptTimeout(timeOut, TimeUnit.SECONDS);
    }

    /**
     * pageLoadTimeout。頁面加載時的超時時間。由於webdriver會等頁面加載完畢在進行後面的操做,
     * 因此若是頁面在這個超時時間內沒有加載完成,那麼webdriver就會拋出異常
     */

    public void waitForPageLoading(int pageLoadTime) {
        driver.manage().timeouts().pageLoadTimeout(pageLoadTime, TimeUnit.SECONDS);

    }

    /** 根據元素來獲取此元素的定位值 */
    public String getLocatorByElement(WebElement element, String expectText) {
        String text = element.toString();
        String expect = null;
        try {
            expect = text.substring(text.indexOf(expectText) + 1, text.length() - 1);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("failed to find the string [" + expectText + "]");

        }

        return expect;

    }
    /**
     * 獲取當前頁面的URL
     * */
    public String getPageURL(){
        return driver.getCurrentUrl();
        
    }
    /**
     * 這是一堆相同的elements中 選擇 其中方的 一個 而後在這個選定的中 繼續定位
     * */
    public WebElement getOneElement(By bys, By by, int index) {
        return findElementsBy(bys).get(index).findElement(by);
    }

    /**
     * 上傳文件,須要點擊彈出上傳照片的窗口才行
     * 
     * @param brower
     *            使用的瀏覽器名稱
     * @param file
     *            須要上傳的文件及文件名
     */
    public void handleUpload(String browser, File file) {
        String filePath = file.getAbsolutePath();
        String executeFile = "res/script/autoit/Upload.exe";
        String cmd = "\"" + executeFile + "\"" + " " + "\"" + browser + "\"" + " " + "\"" + filePath + "\"";
        try {
            Process p = Runtime.getRuntime().exec(cmd);
            p.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * @Description 對於windows GUI彈出框,要求輸入用戶名和密碼時,
     *              seleniumm不能直接操做,須要藉助http://modifyusername:modifypassword@yoururl 這種方法
     * 
     * */
    public void loginOnWinGUI(String username, String password, String url) {
        driver.get(username + ":" + password + "@" + url);
    }

    /** 檢查元素是否顯示 */
    public boolean isDisplayed(WebElement element) {
        boolean isDisplay = false;
        if (element.isDisplayed()) {
            logger.info("The element: [" + getLocatorByElement(element, ">") + "] is displayed");
            isDisplay = true;
        } else if (element.isDisplayed() == false) {
            logger.warn("The element: [" + getLocatorByElement(element, ">") + "] is not displayed");

            isDisplay = false;
        }
        return isDisplay;
    }
    
    /**檢查元素是否是存在*/
    public  boolean doesElementsExist(By byElement){
        try{
        findElementBy(byElement);
        return true;
        }catch(NoSuchElementException nee){
            
            return false;
        }
        
        
    }
    
    /** 檢查元素是否被勾選 */
    public boolean isSelected(WebElement element) {
        boolean flag = false;
        if (element.isSelected() == true) {
            logger.info("The element: [" + getLocatorByElement(element, ">") + "] is selected");
            flag = true;
        } else if (element.isSelected() == false) {
            logger.info("The element: [" + getLocatorByElement(element, ">") + "] is not selected");
            flag = false;
        }
        return flag;
    }

    /**
     * 判斷實際文本時候包含指望文本
     * 
     * @param actual
     *            實際文本
     * @param expect
     *            指望文本
     */
    public void isContains(String actual, String expect) {
        try {
            Assert.assertTrue(actual.contains(expect));
        } catch (AssertionError e) {
            logger.error("The [" + actual + "] is not contains [" + expect + "]");
            Assert.fail("The [" + actual + "] is not contains [" + expect + "]");
        }
        logger.info("The [" + actual + "] is contains [" + expect + "]");
    }
    
    /**
     * 判斷實際文本,不包含指望文本
     * 
     * @param actual
     *            實際文本
     * @param expect
     *            指望文本
     */
    public void isNotContains(String actual, String expect) {
        try {
            Assert.assertFalse(actual.contains(expect));
        } catch (AssertionError e) {
            logger.error("The [" + actual + "] is  contains [" + expect + "]");
            Assert.fail("The [" + actual + "] is  contains [" + expect + "]");
        }
        logger.info("The [" + actual + "] is not contains [" + expect + "]");
    }

    /** 得到屏幕的分辨率 - 寬 */
    public  double getScreenWidth() {
        return java.awt.Toolkit.getDefaultToolkit().getScreenSize().getWidth();
    }
    
    /**進入新窗口*/
    public void switchNewWindow(By byElement){
        //獲取當前頁面句柄
         current_handles = driver.getWindowHandle();
        //點擊某個連接會彈出一個新窗口
        click(byElement);
        //接下來會有新的窗口打開,獲取全部窗口句柄
        Set<String> all_handles = driver.getWindowHandles();
        //循環判斷,把當前句柄從全部句柄中移除,剩下的就是你想要的新窗口
        Iterator<String> it = all_handles.iterator();
        while(it.hasNext()){
        if(current_handles == it.next()) continue;
        //跳入新窗口,並得到新窗口的driver - newWindow
         window = driver.switchTo().window(it.next());
        }
        
    }
    
    /**回到原始窗口*/
    public void backToOriginalWindow(){
        window.close();
        driver.switchTo().window(current_handles);
        
    }
    
    /**中止頁面加載*/
    public void stopLoad(){    
        pause(1);
        Robot r;
        try {
            r = new Robot();
            r.keyPress(KeyEvent.VK_ESCAPE);
            logger.info("按下了Esc鍵");
            r.keyRelease(KeyEvent.VK_ESCAPE);
            logger.info("鬆開了Esc鍵");
        } catch (AWTException e) {
            e.printStackTrace();
        }

        logger.info("正在中止頁面加載...");
    }

    /**獲取系統時間*/
    public int getDate(String getOption){
         Calendar a=Calendar.getInstance();
         int result=0;
        switch(getOption){
        
        case "年":
            result = a.get(Calendar.YEAR);
            break;
        case "月":
            result = a.get(Calendar.MONTH)+1;
            break;
        case "日":
            result = a.get(Calendar.DATE);
            break;
            default:
                Assert.fail("只支持輸入年、月、日。你輸入了:"+getOption);
        
        }
        
        return result;
    }
    /**判斷alert是否出現*/
    public boolean isAlertPresent(){
        try
        {
            driver.switchTo().alert();
            logger.info("alert出現");
            return true;
        }   
        catch (NoAlertPresentException Ex)
        {
            logger.warn("alert沒有出現");
            return false;
        }   
}

    
    
    /**CMP幹部績效管理系統登陸操做*/
    public void loginCMP(String username,String password){    
        FindElementUtil3TimesTry(30, By.id("account"));
        FindElementUtil3TimesTry(30, By.id("password"));
        FindElementUtil3TimesTry(30, By.id("bLogin"));    
        type(By.id("account"),username);
        type(By.id("password"),password);
        click(By.id("bLogin"));
    }
    
    /**
     * 在多個相同元素中,定位到指定的元素
     * @param by
     * @param index
     * @return
     */
    public WebElement getOneElement(By by, int index) {
         List<WebElement> element = driver.findElements(by);
         return element.get(index);
    }
    
    /**
     * 獲取指定table某一整列的值
     */
    public String getColumnText(By by){
        String values = null;
        List<WebElement> elements = findElementsBy(by);
        for(WebElement e: elements){
            String value = e.getText();
            if(value.length() > 0){
                values = values + "," + value;
            }            
        }
        return values.replace("null,", "");
    }
    
    /**
     * 獲取指定table某一行的值
     * @param index:行號,行號從1開始(0表明table的表頭)
     */
    public String getRowText(By by, int index){
        String values = null;
        List<WebElement> rows = findElementsBy(by);  //tr對象
        WebElement row = rows.get(index); 
        if(row.findElements(By.tagName("td")).size()>0){
            List<WebElement> cells = row.findElements(By.tagName("td"));  //td對象
            for(WebElement cell:cells){
                String value = cell.getText();
                if(value.length() > 0){
                    values = values + "," + value;
                }
                
            }
        }
        return values.replace("null,", "");
    }
    
    /**
     * 獲取指定table個單元格的值
     * @param index:行號,行號從1開始(0表明table的表頭)
     */
    public String getCellText(By by, int RowID, int ColID){
        String value = null;
        //獲得table元素對象
        WebElement table = driver.findElement(by);
        //獲得table表中全部行對象,並獲得所要查詢的行對象。
        List<WebElement> rows = table.findElements(By.tagName("tr"));
        WebElement theRow = rows.get(RowID);
        //調用getCell方法獲得對應的列對象,而後獲得要查詢的文本。
        value = getCell(theRow, ColID).getText();    
        return value.replace("null,", "");
    }
    

    /**
     * 
     * @param Row: 一行的對象
     * @param ColID:對應列
     * @return
     */
    private WebElement getCell(WebElement Row,int ColID){
        List<WebElement> cells;
        WebElement target = null;
        //列裏面有"<th>"、"<td>"兩種標籤,因此分開處理。
        if(Row.findElements(By.tagName("th")).size()>0){
        cells = Row.findElements(By.tagName("th"));        
        target = cells.get(ColID);
        }
        if(Row.findElements(By.tagName("td")).size()>0){
        cells = Row.findElements(By.tagName("td"));
        target = cells.get(ColID);
        }
        return target;
    }

    /**
     * 在給定的時間內去查找元素,若是沒找到則超時,拋出異常
     * */
    public boolean isShown(int timeOut, final By By) {
        boolean flag = true;
        logger.info("開始查找元素[" + 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) {
            flag = false;

        }    
        return flag;
    }
    
    
    /**頁面過長時候滑動頁面 window.scrollTo(左邊距,上邊距); */
    public void scrollPage(int x,int y){
        String js ="window.scrollTo("+x+","+y+");";
        ((JavascriptExecutor)driver).executeScript(js);
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
View Code
相關文章
相關標籤/搜索