Appium自動化-----資料驅動讀取外部Excel檔案

來源:互聯網
上載者:User

標籤:學習記錄

=====要進行操作的Excel======

650) this.width=650;" src="https://s2.51cto.com/oss/201711/16/a369157c05c8aeffc8757150021cca8a.png-wh_500x0-wm_3-wmp_4-s_1059370577.png" title="QQ圖片20171116174705.png" alt="a369157c05c8aeffc8757150021cca8a.png-wh_" />

=====對以上Excel的操作==============

//Excel的檔案操作
public class ExcelUtilTest {
    
    private XSSFWorkbook excelWBook;//Excel工作薄
    private XSSFSheet excelWSheet;//工作表
    private XSSFRow row;//行
    private XSSFCell cell;//列
    private String filePath;//Excel工作薄路徑
    
    /**構造方法*/
    //設定要操作的Excel的檔案路徑和Excel檔案中的sheet名稱
    //在讀寫Excel的時候,均需要調用此方法,設定要操作的Excel檔案路徑和要操作的sheet名稱
    public ExcelUtilTest(String path,String sheetName) throws Exception{
        FileInputStream excelFile;
        this.filePath=path;
        
        try {
            //執行個體化Excel檔案的FileInputStream對象
            excelFile = new FileInputStream(path);
            //執行個體化Excel檔案的XSSFWorkbook對象
            excelWBook = new XSSFWorkbook();
            //執行個體化Excel檔案的XSSFSheet對象,指定Excel檔案中的sheet名稱;
            excelWSheet = excelWBook.getSheet(sheetName);
            
        } catch (Exception e) {
            throw (e);
        }
    }
    
    
    /**讀取Excel檔案指定儲存格的函數,此函數只支援尾碼為xlsx的Excel檔案*/
    public String getCellData(int rowNum,int cellNum)throws Exception{
        try {
            //通過函數參數指定儲存格的行號和列表,擷取指定的儲存格對象
            cell = excelWSheet.getRow(rowNum).getCell(cellNum);
            //如果儲存格的內容為字串類型,則使用getStringCellValue()擷取儲存格的內容
            //如果儲存格的內容為數字類型,則使用getNumericCellValue()擷取儲存格的內容
            String cellData="";
            /**擷取儲存格類型*/
            if(cell.getCellType() == XSSFCell.CELL_TYPE_STRING){
                cellData = cell.getStringCellValue();
            }else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC){
                DecimalFormat df = new DecimalFormat("0");//保留小數的方法,0為不保留小數
                cellData = df.format(cell.getNumericCellValue());//format()格式化
            }
            return cellData;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }

    }
    
    /**在Excel檔案的執行儲存格中寫輸入資料,此函數只支援尾碼為xlsx的檔案寫入
     * @param result 結果
     * @param rowNum 行數
     * @param cellNum 列數
     * */
    public void setCellData(int rowNum,int cellNum,String result) throws Exception{
        
        try{
            //擷取Excel檔案中的行對象
            row=excelWSheet.getRow(rowNum);
            //如果儲存格為空白,則返回Null
            cell = row.getCell(cellNum,Row.RETURN_BLANK_AS_NULL);
            
            if(cell == null){
                //當儲存格對象是null的時候,則建立儲存格,因為儲存格為空白,無法調用儲存格對象的setCellValue方法設定儲存格的值
                cell=row.createCell(cellNum);
                //建立儲存格後可以調用儲存格對象的setCellValue方法設定儲存格的值
                cell.setCellValue(result);
            }else{
                //儲存格中如果有內容,則可以直接調用儲存格對象的setCellValue方法設定儲存格的值
                cell.setCellValue(result);
                System.out.println("儲存格值設定完成");
            }
            
            //執行個體化寫入Excel檔案的檔案輸出資料流對象
            FileOutputStream fileOut = new FileOutputStream(filePath);
            //將內容寫入Excel檔案中
            excelWBook.write(fileOut);
            //調用flush方法強制重新整理寫入檔案
            fileOut.flush();
            //關閉檔案輸出資料流對象
            fileOut.close();
            
        }catch(Exception e){
            e.printStackTrace();
            throw(e);
        }
        
    }
    
    /**從Excel檔案擷取測試資料的靜態方法
     * @throws IOException
     * */
    public static Object[][] getTestData(String excelFilePath,String sheetName) throws IOException{
        //根據參數傳入的資料檔案路徑和檔案名稱,組合出Excel資料檔案的絕對路徑
        File file=new File(excelFilePath);
        
        //建立FileInputStream對象用於讀取Excel檔案
        FileInputStream inputStream = new FileInputStream(file);
        
        //聲明Workbook對象
        Workbook workBook = null;
        
        //擷取檔案類型的尾碼名;
        String fileExtensionName = excelFilePath.substring(excelFilePath.indexOf("."));
        
        //判斷如果是xlsx,則使用 XSSFWorkbook 對象進行執行個體化
        //如果是xls,則使用 SSFWorkbook 對象進行執行個體化
        if(fileExtensionName.equals(".xlsx")){
            
            workBook = new XSSFWorkbook(inputStream);
            
        }else if(fileExtensionName.equals(".xls")){
            workBook = new HSSFWorkbook(inputStream);
        }
        
        //通過sheetName參數,產生sheet對象
        Sheet sheet = workBook.getSheet(sheetName);
        
        //擷取Excel資料檔案中sheet1中資料的行數,getLastRowNum方法擷取資料的最後行號
        //getFirstRowNum方法擷取資料的第一行行號,相減之後算出資料的行數
        int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum();
        System.out.println(sheet+"總行數是"+rowCount);
        
        //建立名為records的list對象來儲存從Excel資料檔案中擷取的資料
        List<Object[]> records = new ArrayList<Object[]>();
        
        //使用2個for迴圈遍曆Excel資料檔案中的所有資料(除了第一行,第一行是資料列名稱),所以從1開始
        for(int i =1;i<=rowCount;i++){
            //使用getRow()擷取行對象
            Row row=sheet.getRow(i);
            
            /*聲明一個數組,來儲存Excel資料檔案每行中的測試案例和資料,數組的大小用getLastCellNum-1來進行動態聲明,實現測試資料個數和數組大小相一致
             * 因為Excel資料檔案中的測試資料航的最後一個儲存格為測試執行結果,倒數第二個儲存格為此測試資料行
             * 是否啟動並執行狀態。所最後兩列的儲存格資料並不需要傳入到測試方法中,所以使用getLastCellNum-2的方法去掉每行中的最後兩個儲存格資料
             * 計算出需要儲存的測試資料個數,並作為測試資料數組的初始化大小
            */
            String fields[]=new String[row.getLastCellNum()-2];//建立一個String類型的數組,並指定大小
            
            /*if用來判斷資料行是否要參加測試的執行,Excel檔案的倒數第二行為資料行的狀態位,標記為*
             * “y”表示此資料要被測試指令碼執行,標記為非“y”的資料行均被認為不會參與測試指令碼的執行,會被跳過
             * */
            String yesOrNot=row.getCell(row.getLastCellNum()-2).getStringCellValue();
//            System.out.println(row.getCell(row.getLastCellNum()-2).getCellType()==XSSFCell.CELL_TYPE_NUMERIC);
            
            if(row.getCell(row.getLastCellNum()-2).getStringCellValue().equals("y")){    
                for(int j=0;j<row.getLastCellNum()-2;j++){
                    //判斷Excel的儲存格欄位是數字還是字元,字串格式調用getStringCellValue()擷取
                    //數字格式調用getNumericCellValue()擷取
                    //System.out.println(row.getCell(j).getCellType()== XSSFCell.CELL_TYPE_NUMERIC);
                    if(row.getCell(j).getCellType() == XSSFCell.CELL_TYPE_STRING){
                        fields[j]=row.getCell(j).getStringCellValue();        
                    }else if(row.getCell(j).getCellType() == XSSFCell.CELL_TYPE_NUMERIC){
                        DecimalFormat df= new DecimalFormat("0");
                        fields[j]=df.format(row.getCell(j).getNumericCellValue());
                    }else{
                        System.out.println("格式錯誤");
                    }
                    //System.out.println(fields[j]);
                }
                
                //fields的資料Object Storage Service到records的list中
                records.add(fields);
            }
            
        }
        
        //定義函數傳回值,即object[][]
        //將儲存測試資料的list轉換為一個Object的二維資料
        Object[][] results=new Object[records.size()][];
        
        //設定二維資料每行的值,每行是個object對象
        for(int i=0;i<records.size();i++){
            results[i]=records.get(i);
        }
        //關閉Excel檔案
        inputStream.close();
        return results;
    }
    
    
    //遍曆二維數組
    public void printArray(Object[][] arr){
        for (int x = 0; x < arr.length; x++) {  
            for (int y = 0; y < arr[x].length; y++) {  
                System.out.print(arr[x][y] + " ");  
            }  
            System.out.println("");  
        }  
    }
}



======Excel的檔案操作類的--測試類別=====

public class TestExcelUticl {

    public static void main(String[] args) throws Exception {
        ExcelUtilTest eut = new ExcelUtilTest("configs/測試案例.xlsx", "登入資料");//excel名字,sheet名字
//        eut.getCellData(3, 3);
        Object[][] arr=eut.getTestData("configs/測試案例.xlsx", "登入資料");
        eut.printArray(arr);
    }

}


=====應用到自動化資料驅動裡,實現自動化資料驅動讀取外部Excel檔案=========


     /**尋找元素*/
    @Test(dataProvider="loginTestData")
    public static void testCase(String loginTestData1,String loginTestData2){
            Thread.sleep(5000);//等待
        //進入
        driver.findElementById("元素定位id").click();
        //手機號
        AndroidElement modile= driver.findElementById("元素定位id");
        modile.clear();
        modile.sendKeys(loginTestData1);
        //驗證碼
        AndroidElement pws=driver.findElementById("元素定位id");
        pws.clear();
        pws.sendKeys(loginTestData2);
        //點擊登入
        driver.findElementById("元素定位id").click();
        
    }
    
    /**登入資料驅動
     * */
    @DataProvider(name="loginTestData")  
    public static Object[][] data() throws IOException  
    {  
        Object[][] arr=ExcelUtilTest.getTestData("configs/測試案例.xlsx", "登入資料");
        return  arr;
    } 


Appium自動化-----資料驅動讀取外部Excel檔案

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.