Ashwin Ashwin -4 years ago 395
Java Question

How to pass selenium webdriver instance to another class

I browsed through the site but did not find the answer I am looking.

I have


  1. Superbase class- here I just create object of a webdriver

  2. Baseclass- In this class I extend Superbase class, invoke the driver, and open the URL.

  3. Clicklink class- In this class, I again extend the Superbase Class but only to find a null pointer exception. I think I am getting the exception as the driver object is not initialized.



I am just a beginner, and have not tried the browserfactory and other options, as I want to start with simple flow.

Superclass

Public class Superclass
{
public webdriver Driver;
}


Baseclass

public class Baseclass extends Superclass
{
setting capabilities and launching the browser
}


ClickLink

public class Clicklink extends Superclass
{
here I want to click on a link
driver.findelement(by.xpath("xpath").click());
// after this statement I get a null pointer exception
}


Can you please guide me here? how can I achieve the same.

Thanks much!

Answer Source

This is lot of guesswork done from my side, but please make sure, that your Superclass actually sets the driver and returns it. You can actually make it in both methods:

public class Superclass
{
  public WebDriver driver;
  public Superclass(){
    driver = new FirefoxDriver();
  }
  public WebDriver getdriver(){
    if (driver == null){
      driver = new FirefoxDriver();
      return driver;
    }else{
      return driver;
    }
  }
}

And later in methods you call it by:

public class Clicklink extends Superclass
{

getdriver().findelement(by.xpath("xpath").click());

}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download