Java 使用 Common Selenium WebDriver 实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20730665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Common Selenium WebDriver instance
提问by user2850361
I want use a common WebDriver instance across all my TestNG tests by extending my test class to use a base class as shown below but it doesn't seem to work :
我想通过扩展我的测试类来使用一个基类,在我所有的 TestNG 测试中使用一个通用的 WebDriver 实例,如下所示,但它似乎不起作用:
public class Browser {
private static WebDriver driver = new FirefoxDriver();
public static WebDriver getDriver()
{
return driver;
}
public static void open(String url)
{
driver.get(url);
}
public static void close()
{
driver.close();
}
}
I want to use the WebDriver in my test class as shown below, but I get the error message : The method getDriver() is undefined for the type GoogleTest:
我想在我的测试类中使用 WebDriver,如下所示,但我收到错误消息: getDriver() 方法未定义为 GoogleTest 类型:
public class GoogleTest extends Browser
{
@Test
public void GoogleSearch() {
WebElement query = getDriver().findElement(By.name("q"));
// Enter something to search for
query.sendKeys("Selenium");
// Now submit the form
query.submit();
// Google's search is rendered dynamically with JavaScript.
// Wait for the page to load, timeout after 5 seconds
WebDriverWait wait = new WebDriverWait(getDriver(), 30);
// wait.Until((d) => { return d.Title.StartsWith("selenium"); });
//Check that the Title is what we are expecting
assertEquals("selenium - Google Search", getDriver().getTitle().toString());
}
}
采纳答案by Simon Forsberg
The problem is that your getDriver
method is static.
问题是你的getDriver
方法是static。
Solution #1: Make method non-static (this will either need to make the driver
variable non-static as well, or use return Browser.getDriver();
)
解决方案#1:使方法非静态(这也需要使driver
变量非静态,或使用return Browser.getDriver();
)
public WebDriver getDriver() {
return driver;
}
Or,call the getDriver
method by using Browser.getDriver
或者,getDriver
通过使用调用该方法Browser.getDriver
WebElement query = Browser.getDriver().findElement(By.name("q"));
回答by Andrian Durlestean
You need to start your driver, one of many solution is to try @Before to add, Junit will autorun it for you.
您需要启动您的驱动程序,许多解决方案之一是尝试添加@Before,Junit 将为您自动运行它。
public class Browser {
private WebDriver driver;
@Before
public void runDriver()
{
driver = new FirefoxDriver();
}
public WebDriver getDriver()
{
return driver;
}
public void open(String url)
{
driver.get(url);
}
public void close()
{
driver.close();
}
}