Home > Software engineering >  How to replace static driver method
How to replace static driver method

Time:07-21

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.

CodePudding user response:

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