在webdriver实际
测试项目中,创建testCase,需要不断的进行new
浏览器驱动创建浏览器,才能进行浏览器操作,这时问题就来了,单存在上百,上千个case的时候呢?如何保证浏览器驱动的唯一性能?这时候引入单例设计模式,可以很好的解决这一类问题。
1、baseInfo.properties文件内容配置
BROWSER_TYPE =Firefox
#BROWSER_TYPE=IE
#BROWSER_TYPE=Chrome
2、读取Properties文件内容的方法。
public class BasePropertiesFile {
// 读取Properties文件内容
public String readPropertiesFile(String propertiesFilePath, String key) {
Properties properties = new Properties();
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(propertiesFilePath);
properties.load(fileInputStream);
if (properties.containsKey(key)) {
return properties.getProperty(key);
} else {
System.out.println("传入的Key值不存在!");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return properties.getProperty(key);
}
}
3、判断浏览器属于哪一种类型,分为:IE 火狐,
谷歌浏览器,三种。
public class DriverTools {
public static WebDriver driver;
String propertiesFilePath = "D:\\eclipes\\20160413\\20160413\\PrppertiesFiles\\baseInfo.properties";
BasePropertiesFile basePropertiesFile = TestWebDriver.getDriver();
String value = basePropertiesFile.readPropertiesFile(propertiesFilePath, "BROWSER_TYPE");
public WebDriver getDriver() {
if (value.equals("IE")) {
DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
ieCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
return driver = TestWebDriver.getDriver();
} else if (value.equals("Chrome")) {
return driver TestWebDriver.getDriver();
} else {
System.setProperty("webdriver.firefox.bin", "C:/Program Files/Mozilla Firefox/firefox.exe");
return driver = new FirefoxDriver();
}
}
}
4、单利模式设计,通过私有化构造方法,保证对象的唯一性。
public class TestWebDriver {
// 私有化构造方法
private TestWebDriver() {
}
private static WebDriver testDriver = null;
public static WebDriver getDriver() {
if (testDriver == null) {
testDriver = new DriverTools().getDriver();
}
return testDriver;
}
}
5、测试通过单利模式设计,是否可以获取到浏览器驱动,启动浏览器。
public class TestMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver=TestWebDriver.getDriver();
driver.get("http://www.baidu.com");
}
}