2

I am getting this error when running the below selenium scripts using TestNG with Selenium Grid. I'm extending the testbase class to access the WebDriver, but I'm not sure if each class is getting the WebDriver instance correctly since I'm getting a NullPointerException?

The tests scrolls to the first item to click and doesn't click it. I'm new to Java, please advise. I am wondering if I'm understanding inheritance and initiation of objects correctly. Thanks for your help.

java.lang.NullPointerException

3

Agree with @Dale Emery.

Use this code:

public class WatchTV {

    WebDriver driver;
    WebDriverWait wait;
    int waitseconds = 60;

    public WatchTV(WebDriver driver){
        this.driver = driver;
        wait = new WebDriverWait(driver, waitseconds);
    }

    By watchtvlink = By.linkText("Watch TV »");

    public WebElement WatchTVLink()
    {
        wait.until(ExpectedConditions.elementToBeClickable(watchtvlink));
        return driver.findElement(watchtvlink);
    }

}
  • Thank you so much for your help. I'm new to coding. I've been stuck on this for awhile. Thank you. – seleniumappiumnewbie Jun 17 '16 at 20:51
  • If I have multiple methods in WatchTV class, how can I use WebDriverWait in all the methods without having to copy the same code into each method? Thanks. – seleniumappiumnewbie Jun 17 '16 at 21:05
  • I changed my answer according to your question – kotoj Jun 17 '16 at 21:53
2

Your Setup() method runs (and initializes the driver) only in the Pg_WatchTV_Test class.

Merely extending TestBase does not cause TestNG to run your setup method. It runs setup methods (annotated by @BeforeMethod and the like) only if the class has test methods.

Your WatchTV class has no tests, so TestNG does not treat it as a test class. So the Setup() method in WatchTV never runs. So your WatchTV instance has no driver.

Rather than making WatchTV extend TestBase to get a driver:

  1. Write a WatchTV constructor that takes a WebDriver parameter.
  2. Do one or the other of:
    • Create the WebDriverWait instance in the constructor, using the passed driver.
    • In the constructor, save the driver to a field. Then in the WatchTVLink() method, create the WebDriverWait instance using the driver field. (See kotoj's excellent example.)
  • 1
    The same answer I've just written in the same time, but without example code, so I posted also my answer. – kotoj Jun 17 '16 at 20:40
  • Thank you so much for your help. I'm new to coding. I've been stuck on this for awhile. Thank you. – seleniumappiumnewbie Jun 17 '16 at 20:51
  • If I have multiple methods in WatchTV class, how can I use WebDriverWait in all the methods without having to copy the same code into each method? Thanks. – seleniumappiumnewbie Jun 17 '16 at 21:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.