mac java+selenium 實現UI自動化2_琉璃

使用excel驅動的話首先要下載JXL.jar包,導入maven項目中,可以直接拖到resouces裏,然後右鍵add as library;然後把excel文件也同樣拖到resouces裏,然後代碼編寫獲取路徑;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Date;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;


public class Test {

    public String time = null;//創建測試結果報告保存到本地

    public void createReport() throws IOException {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//設置日期格式
        time=df.format(new Date());
        File parentDir = new File("/Users/liuli/Desktop/UIreport");//報告存儲的文件地址
        parentDir.mkdir();
        String hash = "Report_" + time;
        String fileName = hash + ".txt";
        File file = new File(parentDir, fileName);
        try {
            file.createNewFile();
            System.out.print("create report successful!");
        }
        catch (IOException e){
            throw new IOException("Exception: " + e);
        }
    }
    //把元素以屬性來分類編寫入方法,然後遍歷excel去讀取詳細的元素

    public void buttonClick_xpath(String path,ChromeDriver driver) throws IOException {
        try{
            if (driver.findElement(By.xpath(path))!=null){
                driver.findElement(By.xpath(path)).click();
                writeToFile(path, "is clicked");

            }
            else {
                writeToFile(path,"is not found");
            }
        }catch (IOException e){
            e.printStackTrace();
        }

    }
  /*  public void buttonClick_id(String path,ChromeDriver driver) throws IOException {
        try{
            if (driver.findElement(By.id(path))!=null){
                driver.findElement(By.id(path)).click();
                writeToFile(path, "is clicked");
            }
            else {
                writeToFile(path,"is not found");
            }
        }catch (IOException e){
            e.printStackTrace();
        }

    }*/
    public void buttonClick_className(String path,ChromeDriver driver) throws IOException {
        try{
            if (driver.findElement(By.className(path))!=null){
                driver.findElement(By.className(path)).click();
                writeToFile(path, "is clicked");
            }
            else {
                writeToFile(path,"is not found");
            }
        }catch (IOException e){
            e.printStackTrace();
        }

    }
    public void buttonClick_linkText(String path,ChromeDriver driver) throws IOException {
        try{
            if (driver.findElement(By.linkText(path))!=null){
                driver.findElement(By.linkText(path)).click();
                writeToFile(path, "is clicked");
            }
            else {
                writeToFile(path,"is not found");
            }
        }catch (IOException e){
            e.printStackTrace();
        }

    }
//輸入用戶名和密碼
    public void input_id(String path,String input,ChromeDriver driver) throws IOException {
        try{
            if (driver.findElement(By.id(path))!=null){
                driver.findElement(By.id(path)).sendKeys(input);
                writeToFile(path, "is keyed in");
            }
            else {
                writeToFile(path,"is not keyed in");
            }
        }catch (IOException e){
            e.printStackTrace();
        }

    }
    public void clear(String name, ChromeDriver driver) throws IOException{
        driver.findElement(By.id(name)).clear();
        writeToFile(name, "is cleared");
    }

    public void verifyText(String text, ChromeDriver driver) throws InterruptedException, IOException {
        if (driver.getPageSource().contains(text)){
            writeToFile(text, "is found");
        }
        else{
            writeToFile(text, "is not found");
        }
    }

        //點擊後瀏覽器返回首頁
    public void back(String contents, ChromeDriver driver) throws IOException {
      try{
          driver.navigate().back();
          writeToFile(contents, "browser is backed");
      }catch (IOException e){
          e.printStackTrace();
      }

        //back(sheet.getCell(1, j).getContents(), driver);
    }
    public void wait(int milli) throws IOException, InterruptedException{
        Thread.sleep(milli);
        writeToFile(milli+"", "is slept");//死等,這個後期再優化
    }

    public void writeToFile(String item, String action) throws IOException{//寫入報告
        File file=new File("/Users/liuli/Desktop/UIreport/Report_" + time + ".txt");
        BufferedWriter w = new BufferedWriter(new FileWriter(file,true));
        try{
            w.newLine();
            w.write(item+" "+action);

           // w.flush();
            w.close();
        }catch (IOException e){
            e.printStackTrace();
       }finally {
            if(w!=null){
                w.close();
            }
        }
    }


}

main方法

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.openqa.selenium.chrome.ChromeOptions;


public class Function {
    public static void main(String [] args) throws InterruptedException, IOException {
        //有人很得意的告訴我這個方法比我寫的絕對路徑好用,只要下載代碼直接就能用了,謙虛的我接受了這個建議;
        // 建一個maven項目,不選擇任何模版,把chromedriver貼到resources裏,然後獲取這個路徑,工具跟着代碼走。。。
        ClassLoader classLoader=Function.class.getClassLoader();
        URL resource=classLoader.getResource("chromedriver");
        System.out.print("文件路徑"+ resource.getPath()+"\n");
        System.setProperty("webdriver.chrome.chromedriver",resource.getPath());

       // driver.manage().window().maximize();//瀏覽器窗口最大化---後來發現這一行代碼並沒有產生作用,用下面的三行代碼解決了最大化的問題
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--kiosk");
        WebDriver driver = new ChromeDriver(chromeOptions);

        Test test=new Test();
        try{
            test.createReport();
        }catch (IOException e){
            throw new IOException("Exception: "+e);
        }
        //下面的三行代碼是獲取放在resouces文件裏的data數據
        ClassLoader classLoader1=Function.class.getClassLoader();
        URL resource1=classLoader1.getResource("data2.xls");
       // System.setProperty("data2",resource1.getPath());
        File inputWorkbook=new File(resource1.getPath());
        Workbook w;
        try{
            w=Workbook.getWorkbook(inputWorkbook);
            Sheet sheet=w.getSheet(0);
            for (int j = 0; j < sheet.getRows(); j++) {
                Cell cell = sheet.getCell(0, j);
                String value = cell.getContents();
                //The data file first column determines which method to call from test class
                if (value.equals("getUrl")){
                    driver.get(sheet.getCell(1,j).getContents());
                }
                else if(value.equals("buttonClick_xpath")){
                    test.buttonClick_xpath(sheet.getCell(1,j).getContents(), (ChromeDriver) driver);
                }
              /*  else if(value.equals("buttonClick_css")){
                    test.buttonClick_css(sheet.getCell(1, j).getContents(), driver);
                }
                else if(value.equals("buttonClick_id")){
                    test.buttonClick_id(sheet.getCell(1, j).getContents(), (ChromeDriver) driver);
                }*/
                else if(value.equals("wait")){
                    String x = sheet.getCell(1,j).getContents();
                    test.wait(Integer.parseInt(sheet.getCell(1,j).getContents()));
                }
                else if(value.equals("clear")){
                    test.clear(sheet.getCell(1,j).getContents(), (ChromeDriver) driver);
                }
               /* else if(value.equals("input_css")){
                    test.(sheet.getCell(1,j).getContents(),sheet.getCell(2,j).getContents(),driver);
                }*/
                else if(value.equals("input_id")){
                    test.input_id(sheet.getCell(1,j).getContents(),sheet.getCell(2,j).getContents(), (ChromeDriver) driver);
                }/*
                else if(value.equals("input_xpath")){
                    api.input_xpath(sheet.getCell(1,j).getContents(),sheet.getCell(2,j).getContents(),driver);
                }*/
                else if(value.equals("verifyText")){
                    test.verifyText(sheet.getCell(1,j).getContents(), (ChromeDriver) driver);
                }
                else if(value.equals("back")){
                    test.back(sheet.getCell(1,j).getContents(), (ChromeDriver) driver);
                }
                else if(value.equals("buttonClick_className")){
                    test.buttonClick_className(sheet.getCell(1,j).getContents(),(ChromeDriver)driver);
                }
                else if(value.equals("buttonClick_linkText")) {
                    test.buttonClick_linkText(sheet.getCell(1, j).getContents(), (ChromeDriver) driver);
                }
                else{
                    //if reached the end of the file, break out the loop
                    break;
                }
            }
        }catch (BiffException e) {
            e.printStackTrace();
        }
        finally{
            driver.quit();
        }

    }

}

執行後的產生的報告,刻意寫錯一個元素。爲了去驗證下判斷是否正確,結果如我所願,這個元素沒有找到,說明代碼判斷沒問題,哈哈

data 表

代碼執行成功,報告也沒有問題;在操作過程中遇到的小問題:

1.我直接把numbers存儲爲excel格式結果執行時報錯,這個提示也很清奇,說是創建session失敗;查了下說是我excel的格式必須爲.xls,而number導出爲excel時默認爲.xlsx,然後我就直接修改了後綴名,結果仍然報錯沒用;後來重新導出,選擇高級選項,兼容版本,再執行-成功;

2.那個等待時間我寫的是讓線程死等,這個方式感覺很冒傻氣,網上查的代碼不太懂,後期我再研究優化下

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章