In this article we will learn how to create WebDriver Instance multiple classes:
So, we will create a WebDriver instance in one class & call it in multiple class
we have achieve this by 2 ways
1).By using extends
2).By using Singleton class
To know about singleton class Click Here
For Video :- Click Here
Method :1By extends Keyword
Step :1Create a class & initialize your driver
import org.openqa.selenium.chrome.ChromeDriver;
public class MainDriver
{
public static WebDriver driver;
public static void createInstance()
{
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\Complete selenium\\ChromeDriver\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
}
}
Step :2Create an another class & extend above driver class
public class Testcase1 extends MainDriver
{
public static void url()
{
MainDriver.createInstance();
driver.navigate().to("http://www.way2testing.com");
}
}
Step :3Create an another class & extend above driver class
public class TestCase2 extends MainDriver
{
public static void getTitle()
{
System.out.println(driver.getTitle());
}
}
Step :4Create an another class & extend above driver class
import org.testng.annotations.Test;
public class Excution
{
@Test(priority = 0)
public void getUrl()
{
Testcase1.url();
}
@Test(priority = 1)
public void getTitle()
{
TestCase2.getTitle();
}
}
If you will run this Exeution class , you can see that with one WebDriver Instance(driver), you are able to perform your all task.
Method :2By Singleton Class
Step :1Create a Singleton class & initialize your driver
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class SingletonDriver
{
public static WebDriver driver = null;
public static void Initiallize()
{
if(driver == null)
{
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\Complete selenium\\ChromeDriver\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
}
}
public static void close()
{
driver.close();
}
public static void quit()
{
driver.quit();
}
}
Step :2Create a class for your test cases & execute singleclass method
import org.testng.annotations.Test;
public class Testcases
{
@BeforeTest
public void initializeDriver()
{
SingletonDriver.Initiallize();
}
@Test(priority = 0)
public void openurl()
{
SingletonDriver.driver.navigate().to("http://www.way2testing.com");
}
@Test(priority = 1)
public void getTitle()
{
System.out.println(SingletonDriver.driver.getTitle());
}
}
So, by using above methods, you can create a WebDriver Instanse(driver) and can use it in your multiple classes.
Thanks :)
No comments:
Post a Comment