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,就可以正常启动浏览器了。