我正在使用Selenium来实现自动化。挑战是这样的。
FirefoxDriver driver = new FirefoxDriver();
InternetExplorerDriver driver = new InternetExplorerDriver();
ChromeDriver driver = new ChromeDriver();这三个都创建了驱动程序对象。所有的驱动程序对象都有类似的方法。有一段代码将在这些对象实例化之后运行。在程序的一次运行期间,只使用这些驱动程序中的一个。我需要一些逻辑来做到这一点。因为这3个类都没有超类,所以我正在寻找其他的出路。
发布于 2012-10-01 03:15:36
工厂方法模式可以快速解决您的问题。
//Define the interface with the common methods
Interface ISuperDriver
{
void run();
}
//implement the interface on firefox
class FireFoxDriver:ISuperDriver{
void run(){
//firefox driver
}
}
//implement the interface on IE
class InternetExplorerDriver:ISuperDriver{
void run(){
//ie driver
}
}
//chrome
class ChromeDriver:ISuperDriver{
void run(){
//chrome
}
}
//create reference for the interface
ISuperDriver Driver;
if(<input 1>){
Driver= new FireFoxDriver();}//instantiate firefox
else if(<input 2>){
Driver= new InternetExplorerDriver();}//IE
else if(<input 3>){
Driver= new ChromeDriver();}//Chrome
//Finally invoke your method
Driver.Run();发布于 2012-10-01 03:06:24
只需创建一个超类来包装这3个类的功能。
public abstract class Browser {
public abstract Navigate(string link);
}
public class Firefox : Browser {
FirefoxDriver driver;
public Firefox(){
driver = new FirefoxDriver();
}
public abstract Navigate(string link){
driver.GoTo(link);
}
}
public class Chrome : Browser {
ChromeDriver driver;
public Chrome (){
driver = new ChromeDriver();
}
public abstract Navigate(string link){
driver.FollowLink(link);
}
}发布于 2012-10-01 03:17:05
您可以使用以下类型的类:
public abstract class BrowserDriver { ... }
public class InternetExplorerDriver : BrowserDriver { ... }
public class FirefoxDriver : BrowserDriver { ... }
public class ChromeDriver : BrowserDriver { ... }用法:
BrowserDriver driver = null;
switch (BrowserType) // assuming BrowserType is a property of type Browser enum, holding the value from the set {InternetExplorer, Firefox, Chrome}
{
case Browser.InternetExplorer:
driver = new InternetExplorerDriver();
break;
case Browser.Firefox:
driver = new FirefoxDriver();
break;
case Browser.Chrome:
driver = new ChromeDriver();
break;
}
SomeFunction(driver);
// ...
public void SomeFunction(BrowserDriver driver)
{
//... your code here
}https://stackoverflow.com/questions/12664097
复制相似问题