selenium 2 支持多瀏覽器,通過不同的driver方法來啓動不同的瀏覽器。在設計框架的時候如果將這個考慮進去,可以很方便地在不同瀏覽器間切換,就可以方便地進行兼容性測試。
對瀏覽器的操作我們單獨創建一個類Browser,startBrowser方法中加載不同driver,代碼如下:
public class Browser {
public static WebDriver driver;
public static void startBrowser(String type) {
String path;
switch (type) {
case "ie":
path=Utility.getPath("drivers", "IEDriverServer");
System.setProperty("webdriver.ie.driver", path);
driver = new InternetExplorerDriver();
Utility.logInfo("ie browser starting!!-----------------------------");
driver.manage().window().maximize();
case "firefox":
path=Utility.getPath("drivers", "firefox");
System.setProperty("webdriver.firefox.bin", path);
driver =new FirefoxDriver();
Utility.logInfo("firefox browser starting!!-----------------------------");
driver.manage().window().maximize();
default:
break;
}
}
// 通過方法重載設置默認啓動chrome
public static void startBrowser() {
String path=Utility.getPath("drivers", "chromedriver");
System.setProperty("webdriver.chrome.driver", path);
driver=new ChromeDriver();
Utility.logInfo("chrome browser starting!!-----------------------------");
driver.manage().window().maximize();
}
//quit方法是退出driver,一般在某個case測試結束後執行它
public static void closeDriver() {
driver.quit();
Utility.logInfo("==========test end=======");
}
//close方法只是關閉當前窗體
public static void closeBrower() {
driver.close();
}
//調試的時候我們使用main方法
public static void main(String[] args) {
startBrowser();
closeDriver();
}
}
這樣我們通過對startBrowser的操作就實現了不同瀏覽器的啓動。getPath是我在Utility類中設置的一個獲得絕對路徑的靜態方法。我會在其他篇幅中去講解Utility類。
注意:如果在mac或者linux系統中執行chromedriver,默認情況下會報錯“The driver is not executable”,這個是文件權限的問題,執行語句chmod a+x /path/chromedriver,就可以正常啓動瀏覽器了。