首页 > 解决方案 > 将 webdriver 传递给另一个类的正确方法

问题描述

我想将我的 WebDriver 传递给另一个类,而不是将其传递给该类中的各个方法。这意味着当我创建它的实例时将它传递给类的构造函数。这是我的代码,下面是我的问题-

public class StepDefinitions{

    public static WebDriver driver = null;
    CustomWaits waits;

    @Before("@setup") 
    public void setUp() {
        driver = utilities.DriverFactory.createDriver(browserType);
        System.out.println("# StepDefinitions.setUp(), driver = " + driver);
        waits = new CustomWaits(driver);
    }
}


public class CustomWaits {
    WebDriver driver;

    public CustomWaits(WebDriver driver){
        this.driver = driver;
    }
public boolean explicitWaitMethod(String id) {
        boolean status = false;
        try {
            WebDriverWait wait = new WebDriverWait(driver, 30);
            WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(id)));
            status = element.isDisplayed();
        } catch (NullPointerException e){
            e.printStackTrace();
        }
        return status;
    }
    }

我遇到的错误是NullPointerException在@Given、@When 等中调用该类的方法时。这是我无法解决的范围问题。

功能文件:

@test
Feature: Test 

  @setup
  Scenario: Navigate to Webpage and Assert Page Title
    Given I am on the "google" Website
    Then page title is "google"

这是步骤定义:

@Given("^element with id \"([^\"]*)\" is displayed$")
public void element_is_displayed(String link) throws Throwable {
  if (waits.explicitWaitMethod(link)) { 
    // This is where waits becomes null when I put a breakpoint

    driver.findElement(By.id(link)).isDisplayed();
  } else {
    System.out.println("Timed out waiting for element to display");
  }
}

标签: javaseleniumjunitcucumber-jvm

解决方案


我会做这样的事情。

public class StepDefinitions{

    public StepDefinitions() {
        driver = utilities.DriverFactory.createDriver(browserType);
        System.out.println("# StepDefinitions.setUp(), driver = " + driver);
        waits = new CustomWaits(driver);
    }

    public static WebDriver driver = null;
    public static CustomWaits waits;

    @Given("^element with id \"([^\"]*)\" is displayed$")
    public void element_is_displayed(String link) throws Throwable {
       if (waits.explicitWaitMethod(link)) { 
          // This is where waits becomes null when I put a breakpoint

          driver.findElement(By.id(link)).isDisplayed();
       } else {
          System.out.println("Timed out waiting for element to display");
       }
    }

}


public class CustomWaits {
    private static WebDriver driver;

    public CustomWaits(WebDriver driver){
        this.driver = driver;
    }
    public boolean explicitWaitMethod(String id) {
        boolean status = false;
        try {
            WebDriverWait wait = new WebDriverWait(driver, 30);
            WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(id)));
            status = element.isDisplayed();
        } catch (NullPointerException e){
            e.printStackTrace();
        }
        return status;
    }
}

推荐阅读