How to use the same Webdriver from different class - java

I have 2 Java classes; Main.java and Methods.java. At Main.java, I initialize the chrome webdriver and I want to use the same webdriver for a method at Methods.java. Below are the codes.
Under Main.java
Methods getMethods = new Methods();
#BeforeTest
public void Setup()
{
System.setProperty("webdriver.chrome.driver", "C:\\...\\chromedriver.exe");
driver = new ChromeDriver();
driver.get(PropertiesConfig.getObject("websiteUrl"));
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void TestCase1()
{
getMethods.method1();
}
#AfterTest
public void QuitTC() {
getMethods.QuitTC(); }
Under Methods.java
public void method1 (){
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
….. }
public void QuitTC() {
driver.quit();
}
My question is how do I called the initialize Webdriver from Main.java and used it at Methods.java?
Any help with be appreciated! Thanks!

You can do something like this in a utility class (say TestUtil.java)
private static WebDriver wd;
public static WebDriver getDriver() {
return wd;
}
and then you can use following line to get the webdriver in any of the classes mentioned and work on it
WebDriver driver = TestUtil.getDriver();

Declare a global variable for driver like this :
WebDriver driver = null;
#BeforeTest
public void Setup()
{
System.setProperty("webdriver.chrome.driver", "C:\\...\\chromedriver.exe");
driver = new ChromeDriver();
driver.get(PropertiesConfig.getObject("websiteUrl"));
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
Now, you can call method1 from method class like this :
public class Methods{
public Methods(WebDriver driver){
this.driver = driver;
}
public void method1 (){
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
….. }
}
Now once you create the instance of Methods class, constructor would be called and driver reference could be passed.

Try this
Class1 {
public WebDriver driver = null;
public String baseURL="...";
public void openURL() {
System.setProperty("webdriver.chrome.driver", "D:...\\chromedriver.exe");
driver = new ChromeDriver();
driver.get(baseURL);
}
Class2 extends Class1 {
driver.findElement(....);
}

Related

Multiple instances of browser opening up when running test through webdriver manager

I am new to Selenium, so basically whenever I ran my test, it would open up the URL which I have mentioned in my test. In my same Test I have also mentioned to fill the username and Password.
But somehow once the browser gets launched and redirect to the URL, it opens up another instance of blank browser failing my script that element not found.
Please help me here.
///////////////////////////////////////////////////////////////////////////
public class TruefillTest extends BaseClass {
public Truefill truefill()
{
WebDriver driver=InitializeDriver();
return new Truefill(driver);
}
#Test
public void userLoginIntoTheSystem()
{
truefill().dashBoard().Url();
truefill().dashBoard().EnterUsername("bjdgfe#swcwr.com");
truefill().dashBoard().EnterPassword("Test1234");
}
///////////////////////////////////////////////
public class Truefill {
private WebDriver driver;
public Truefill(WebDriver driver) {
this.driver=driver;
}
public DashBoardPage dashBoard()
{
return new DashBoardPage(driver);
}
////////////////////////////////////////////////////////////
public class DashBoardPage {
private final WebDriver driver;
By Username= By.xpath("//input[#name='name']");
By Password= By.xpath("//input[contains(#id,'exampleInputPassword1')]");
public DashBoardPage(WebDriver driver) {
this.driver=driver;
}
public void Url()
{
driver.get("https://rahulshettyacademy.com/angularpractice/");
}
public void EnterUsername(String username)
{
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.findElement(Username).sendKeys(username);
}
public void EnterPassword(String password)
{
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.findElement(Password).sendKeys(password);
}
////////////////////////////////////////////////////////////
public class BaseClass {
WebDriver driver;
public WebDriver InitializeDriver()
{
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
return driver;
}
}
Each call to the truefill() method initializes a new instance of WebDriver. Since your test is calling it multiple times, it will start a new browser instance on each line. Instead, store the DashboardPage in a local variable:
#Test
public void userLoginIntoTheSystem() {
DashBoardPage dashBoardPage = truefill().dashBoard();
dashBoardPage.Url();
dashBoardPage.EnterUsername("bjdgfe#swcwr.com");
dashBoardPage.EnterPassword("Test1234");
}
You might also want to use a setup method to initialize the Truefill instance, rather than creating it on demand:
private Truefill truefill;
#BeforeEach
public void initializeTruefill() {
WebDriver driver = InitializeDriver();
truefill = new Truefill(driver);
}
#Test
public void userLoginIntoTheSystem() {
DashBoardPage dashBoardPage = truefill.dashBoard();
dashBoardPage.Url();
dashBoardPage.EnterUsername("bjdgfe#swcwr.com");
dashBoardPage.EnterPassword("Test1234");
}
This assumes JUnit 5. If you're using JUnit 4, the annotation is #Before instead of #BeforeEach.

Best practice to list my Driver instance as static, especially for dual test execution?

Best practice to list my Driver instance as static, especially for dual test execution?
Driver factory (Used to setup the driver instance):
public class DriverFactory {
public static WebDriver driver;
protected BasePage basePage;
protected LoginPage loginPage;
public WebDriver getDriver() throws Exception {
try {
ReadConfigFile file = new ReadConfigFile();
String browserName = file.getBrowser();
switch (browserName) {
//firefox setup
case "firefox":
if (null == driver) {
System.setProperty("webdriver.gecko.driver", Constant.GECKO_DRIVER_DIRECTORY);
DesiredCapabilities capabilities=DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
driver = new FirefoxDriver();
}
break;
}
}
}
}
Steps class: (Cucumber step class):
public class LoginSteps extends DriverFactory {
#Given("^User navigates to the \"([^\"]*)\" website$")
public void user_navigates_to_the_website(String url) throws Throwable {
BasePage basePage = new BasePage();
basePage.loadUrl(url);
}
}
Base Page(Base page for page objects):
public class BasePage extends DriverFactory {
protected WebDriverWait wait;
protected JavascriptExecutor jsExecutor;
public BasePage() throws IOException {
this.wait = new WebDriverWait(driver, 15);
jsExecutor = ((JavascriptExecutor) driver);
}
}

WebDriver - one instance of driver in many classes

I have 3 classes like below but when I try to run my test I get NullPointer (TestPage->input1). On debug I spotted that I have a second instantion of driver which is null. Can anyone help me what I did wrong and how to fix it? Shouldn't it work properly?
public class BaseScenario {
protected WebDriver driver;
#BeforeMethod
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Ed\\Desktop\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://toolsqa.com/automation-practice-form/");
}
#AfterMethod
public void TearDown() {
driver.quit();
}
}
'
public class TestsPage {
WebDriver driver;
public TestsPage(WebDriver driver)
{
this.driver=driver;
}
public void input1(){
driver.findElement(By.xpath("//*[#id='content']/form/fieldset/div[1]/input[1]")).sendKeys("Kuba");;
}
public WebElement input2(){
WebElement input2 = driver.findElement(By.xpath("//*[#id='content']/form/fieldset/div[1]/input[2]"));
return input2;
}
}
'
public class Tests extends BaseScenario{
TestsPage pagee = new TestsPage(driver);
#Test
public void TC1() throws Exception {
pagee.input1();
pagee.input2().sendKeys("Chudy");
}
}

Use single driver instance in multiple methods & classes

I have created 2 packages each contains a java class file. The Utility class in 1st package initiates the driver & closes the driver with methods- launchDriver() & closeDriver(). In the 2nd package-Example java class file contains call to these methods. The driver is successfully launched using launchDriver() but when the driver is passed to closeDriver method, the value becomes null...
Please provide a solution.The code is as shown,..
public class Utility {
public static WebDriver driver;
public static String driverpath="E:\\Drivers";
#Test
public static WebDriver launchDriver(final String browser,final String url){
if(browser=="firefox"){
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get(url);
}else if(browser=="chrome"){
System.setProperty("webdriver.chrome.driver", driverpath+"\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
driver.get(url);
}else if(browser=="ie"){
System.setProperty("webdriver.ie.driver", driverpath+"\\IEDriverServer.exe");
WebDriver driver=new InternetExplorerDriver();
driver.manage().window().maximize();
driver.get(url);
}else{
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get(url);
}
return driver;
}
#Test
public static WebDriver closeDriver(WebDriver driver){
Utility.driver=driver;
driver.quit();
return driver;
}
}
class Example in tests package
public class Example{
#Test
public static void launchConfig(){
Utility.launchDriver("chrome", "https://www.google.com");
//Utility.launchDriver("firefox","www.google.com");
Utility.closeDriver(Utility.driver);
}
}
Create an abstract test class and have your test classes extend that. your abstract test class might look like this:
public abstract class Abstract test {
//delcare driver
public static WebDriver driver;
//Assign the correct driver
#BeforeSuite
public void webdriverSetUp() {
if(browser=="firefox"){
WebDriver driver=new FirefoxDriver();
} else if(browser=="chrome"){
WebDriver driver=new ChromeDriver();
} else if(browser=="ie"){
WebDriver driver=new InternetExplorerDriver();
} else{
WebDriver driver=new FirefoxDriver();
}
}
//call getDriver() in your tests
public static WebDriver getDriver() {
return driver;
}
}
Just dont forget your probably going to want to clear all cookies between test methods.

Using Common Selenium WebDriver instance

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 :
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:
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());
}
}
The problem is that your getDriver method is 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(); )
public WebDriver getDriver() {
return driver;
}
Or, call the getDriver method by using Browser.getDriver
WebElement query = Browser.getDriver().findElement(By.name("q"));
You need to start your driver, one of many solution is to try #Before to add, Junit will autorun it for you.
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();
}
}

Categories