Web自動化-Selenium自動化測試-4-編寫測試用例

鹿少年發表於2020-12-03

首先要獲取Driver,這裡主要採用兩種瀏覽器

package selenium.driver;

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

public class Driver {
    public static  WebDriver driver;
    public static void setFirfoxDriver(){
        System.setProperty("webdriver.firefox.bin", "C:\\Program Files\\Mozilla Firefox\\firefox.exe");//這一句適用於火狐未安裝在預設路徑下的情況
        System.setProperty("webdriver.gecko.driver",  "src/main/resources/driver/geckodriver.exe");//定義驅動位置,最新版火狐需要使用GeckoDriver來驅動

    }
    public static void setChromDriver(){
        System.setProperty("webdriver.chrome.driver", "src/main/resources/driver/chromedriver.exe");
    }
    public static WebDriver getDriver(String type){

        if(driver==null){
            switch (type){
                case "Chrome": setChromDriver();driver = new ChromeDriver();
                    break;
                case "FirFox":setFirfoxDriver();driver = new FirefoxDriver();
                    break;
                default: setChromDriver();driver = new ChromeDriver();
            }
            ;
        }
        return  driver;
    }

}

測試driver獲取:

package selenium.driver;

import org.apache.log4j.Logger;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import utils.LoggerUtil;


public class DriverTest {
    Logger logger ;
    @BeforeClass
    public void setup(){
        logger= LoggerUtil.getLogger(DriverTest.class);
    }
    @Test
    public void testGetDriver() {
//       logger.info(Driver.getDriver("FirFox"));
        logger.info(Driver.getDriver("Chrome"));
    }
}

基類:

package selenium.Base;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import selenium.driver.Driver;

public class Base {
    static  WebDriver driver;
    public static  void getInstance(String type){
        if(driver==null){
            driver= Driver.getDriver(type);
        }
    }
    public static void  openUrl(String url){
        driver.get(url);
    }
    public static By ByID(String id){//query
        return  By.id(id);
    }
    public static WebElement getElementByID(String id){
        return   driver.findElement(ByID(id));
    }
   public static  void sendKey(String id,String text){
       getElementByID(id).click();
       getElementByID(id).sendKeys(text);
       try {
           Thread.sleep(10);
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
   }
   public static void  click(By by){
      driver.findElement(by).click();
   }

    public static  void  tearDown(){
        if(driver!=null){
            driver.close();
        }
    }

}

 

相關文章