How to replace static driver method

Issue

public class CommonFunctions {

  public static WebDriver driver;

  public void openWebsite(String url) {
    driver.get(url);
  }

  public void closeBrowser() {
    driver.close();
  }
}
public class TestCase {

  CommonFunctions commonFunctions = new CommonFunctions();

  @BeforeMethod
  public void openWeb() {
    homePage.openWeb();
  }

  @Test
  public void navigateLoginPage() {
    homePage.login();
  }

  @AfterMethod
  public void closeBrowser() {
    commonFunctions.closeBrowser();
  }
}

I have two class (commonfunction,homepage and testcase). When I run code without "static" at "public static Webdriver driver", the code throw nullpointerexception at function "closeBrowser". How to fix this error. I don’t want use method "public static Webdriver driver" as code.

Solution

You need to initialize your driver variable in your CommonFunctions class.

WebDriver driver = new WebDriver(... etc);

Or, write a constructor that initializes this variable.

public class CommonFunctions 
{
  public WebDriver driver;

  public CommonFunctions() // Constructor
  {
      driver = new WebDriver();
  }

Answered By – Robert Harvey

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published