I am new to java selenium.
I would like to use webdDrierSingleton concept, which will help me to use single driver instance across all classes.
I am not able to get the driver instance, could some one guide me how to get it.
You can define the singleton class by defining the class constructor as Private. Please have a look at the code below:
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;
}
}
Your Test class:
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
}
}
If you want to run your test cases present in different classes then you can use @Guice
for example
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>
Note - for test cases to execute in single browser in testng.xml file we need to mention all the classes in single test