java - 将 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");
}
}
解决方案
我会做这样的事情。
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;
}
}
推荐阅读
- excel - 包含时钟的工作簿会自动重新打开
- arduino - 什么是“调用'println(decode_results *)'没有匹配的函数”?
- django - Django 的 DB API 无法返回所有结果
- c++ - 如何存储http响应并发送到浏览器?
- sql - 当我搜索任何关键词时,我的数据重复了
- sql - ORDER 中无法识别的别名
- java - RichPresence 不再适用于 JDA
- python - selenium.common.exceptions.TimeoutException:消息:脚本超时:30 秒内未收到结果
- php - 地理位置显示不同的城市不是很准确
- javascript - API0005 从 Google Apps 脚本到 BitStamp API 的无效签名连接错误