3

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());
   }
}
1
  • This should work. What IDE or compiler are you using? Are you sure you are referring to the right Browser class? Commented Dec 22, 2013 at 15:13

2 Answers 2

4

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"));
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your replies they all work, but I was wondering if I could use the driver variable directly i.e. WebElement query = driver.findElement(By.name("q"));
Ignore my last comment I have used simons solution
1

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();
        }
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.