【发布时间】:2016-02-04 12:18:33
【问题描述】:
我是 java selenium 的新手。
我想使用 webdDrierSingleton 概念,这将帮助我在所有类中使用单个驱动程序实例。
我无法获取驱动程序实例,谁能指导我如何获取它。
【问题讨论】:
标签: singleton
我是 java selenium 的新手。
我想使用 webdDrierSingleton 概念,这将帮助我在所有类中使用单个驱动程序实例。
我无法获取驱动程序实例,谁能指导我如何获取它。
【问题讨论】:
标签: singleton
单例类:
public class WebDriverSingleton {
public static WebDriver driver;
public static WebDriver getInstance() {
if (driver == null) {
driver = new FirefoxWebDriver();
}
return driver;
}
}
在你的测试类中:
WebDriver driver = WebDriverSingleton.getInstance();
【讨论】:
您可以通过将类构造函数定义为 Private 来定义单例类。请看下面的代码:
public class InstanPage {
private static InstanPage instance = null;
private WebDriver driver;
private InstanPage() {
}
public WebDriver openBrowser() {
driver = new FirefoxDriver();
driver.manage().window().maximize();
return driver;
}
public static InstanPage getInstance() {
if (instance == null) {
instance = new InstanPage();
}
return instance;
}
}
你的测试类:
public class YourTestClass {
private InstanPage automation = InstanPage.getInstance();
private WebDriver driver;
// this will give the comman instance of Browser.
driver=automation.openBrowser();driver.get("WWW.XYZ.COM");
@test
public void testone()
{
// your test code
}
}
【讨论】:
如果你想在不同的类中运行你的测试用例,那么你可以使用@Guice
例如
ParentModule.class
import org.openqa.selenium.WebDriver;
import com.google.inject.Binder;
import com.google.inject.Module;
public class ParentModule implements Module{
@Override
public void configure(Binder binder) {
/** getDriver() is the method which is used for launching the respective browser, this method is written in SetDriver class */
SetDriver setDriver = new SetDriver();
WebDriver driver = setDriver.getDriver();
binder.bind(WebDriver.class).toInstance(driver);
}
}
Example1.class
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import com.google.inject.Inject;
import utility.ParentModule;
@Guice(modules = {ParentModule.class})
public class Example1 {
@Inject
WebDriver driver;
@Test
public void test1() {
System.out.println("webdriver in Example1 class - " + driver);
driver.get("http://www.facebook.com");
}
}
Example2.class
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import com.google.inject.Inject;
import utility.ParentModule;
@Guice(modules = {ParentModule.class})
public class Example2 {
@Inject
WebDriver driver;
@Test
public void test1() {
System.out.println("webdriver in Example2 class - " + driver);
driver.get("http://www.gmail.com");
}
}
TestNG.xml
<suite name="ABC">
<test name="Example">
<classes>
<class name="test.Example1"></class>
<class name="test.Example2"></class>
</classes>
</test>
</suite>
注意 - 对于要在 testng.xml 文件中的单个浏览器中执行的测试用例,我们需要提及单个测试中的所有类
【讨论】: