Thursday, June 7, 2018

Create Selenium WebDriver object using Singleton Java pattern

Hi Friends,

You must be knowing about the java patterns and it's advantage. In this post, I am going to create webDriver object using Singleton java pattern.

Singleton means to define a class that has only one instance and provides a global point of access to it.

Singleton class :


public class WebDriverSingleton {

private static WebDriver driver;
private static WebElement element;

private WebDriverSingleton() {
}

public static void initDriverInstance(Browsers browserName) {
 // code for init driver object
}

public static void openURL(String url){
// open url code
}
public static void quit() {
// code for quit driver
}

public static WebElement findElement(Locator locator, String value) {
// code for findElement 
}

// add all the other required method here
}


Test class :

public class Test_1 {
@BeforeClass
public void Setup() {
WebDriverSingleton.initDriverInstance(Browsers.CHROME);
WebDriverSingleton.openURL("http://newtours.demoaut.com");
}
@Test
public void TestCase_1() {
WebDriverSingleton.findElement(Locator.NAME, "userName").sendKeys("testuser");
WebDriverSingleton.findElement(Locator.NAME, "password").sendKeys("testpassword");
WebDriverSingleton.findElement(Locator.NAME, "login").click();
}
@AfterClass
public void killDriver() {
WebDriverSingleton.quit();
}
}

Click Here to Download code from github 

No comments: