我用SharedDriver实现了cumber-jvm picocontainer,并且在本地运行良好。我想使用配置良好的Selenium Grid,但是我不知道如何修改Shareddriver
类以使用RemoteWebDriver
而不是WebDriver
并连接到Selenium GRID。new RemoteWebDriver(new("http://..../wd/hub"), capability);
不起作用,因为我需要抛出MalFormedException
并且REAL_DRIVER
是静态字段。
任何的想法?谢谢!
public class SharedDriver extends EventFiringWebDriver {
private static final WebDriver REAL_DRIVER = WebDriverFactory.internetExplorerWebDriver();
private static final Thread CLOSE_THREAD = new Thread() {
@Override
public void run() {
REAL_DRIVER.close();
}
};
static {
Runtime.getRuntime().addShutdownHook(CLOSE_THREAD);
}
public SharedDriver() {
super(REAL_DRIVER);
}
@Override
public void close() {
if(Thread.currentThread() != CLOSE_THREAD) {
throw new UnsupportedOperationException(
"WebDriver should not close!"
);
}
super.close();
}
@Before
public void deleteAllCookies() {
manage().deleteAllCookies();
}
@After
public void embedScreenshot(Scenario scenario) {
...
}
}
WebDriverFactory:
class WebDriverFactory {
static {
System.setProperty("webdriver.ie.driver", "src/test/resources/webDrivers/IEDriverServer.exe");
}
static WebDriver internetExplorerWebDriver() {
DesiredCapabilities returnCapabilities = DesiredCapabilities.internetExplorer();
System.setProperty("webdriver.ie.driver", "src/test/resources/webDrivers/IEDriverServer.exe");
returnCapabilities.setCapability("requireWindowFocus", true);
returnCapabilities.setCapability(InternetExplorerDriver.ENABLE_PERSISTENT_HOVERING, false);
returnCapabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
returnCapabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
returnCapabilities.setCapability("ignoreZoomSetting", true);
return new InternetExplorerDriver(returnCapabilities);
}
最佳答案
您可以将return语句包装到try..catch
块中,并在引发异常的情况下返回null
。
class WebDriverFactory {
static {
System.setProperty("webdriver.ie.driver", "src/test/resources/webDrivers/IEDriverServer.exe");
}
static WebDriver internetExplorerWebDriver() {
DesiredCapabilities returnCapabilities = DesiredCapabilities.internetExplorer();
System.setProperty("webdriver.ie.driver", "src/test/resources/webDrivers/IEDriverServer.exe");
returnCapabilities.setCapability("requireWindowFocus", true);
returnCapabilities.setCapability(InternetExplorerDriver.ENABLE_PERSISTENT_HOVERING, false);
returnCapabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
returnCapabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
returnCapabilities.setCapability("ignoreZoomSetting", true);
try {
return new RemoteWebDriver(new URL("http://www.google.com"), returnCapabilities);
} catch (MalformedURLException e) {
return null;
}
}
然后,检查
REAL_DRIVER
值是否不是null
。