【发布时间】:2021-06-25 12:02:18
【问题描述】:
我正在尝试将一个元素传递给我的一个函数。但是,我得到了元素的 NullPointer 异常。
我的测试课
public class VehicleEdit {
WebDriver driver;
Elements element = new Elements();
@When("I search for record")
public void searchForRecord() throws Exception {
try {
driver = DriverFactory.getInstance().getDriver();
RecordEditPage recordEditPage = new RecordEditPage (driver);
recordEditPage.waitToLoad();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
}
我还尝试在将元素的文本传递给 waitToBePresentInDom() 之前打印它。文本打印良好,这意味着元素正在被定位,但 waitToBePresentInDom() 中的元素仍显示为 null。 在调试时,我观察到 recordInfoSectionHeader() 中的元素字段显示数据。但是在 elements.waitToBePresentInDom(driver, this.recordInfoSectionHeader()) 中,它显示第二个参数为空。 如何在waitToLoad()函数的第一行打印相同元素的数据,但在waitToLoad()函数的第二行仍然显示元素为null?
我的页面对象类
public class RecordEditPage {
WebDriver driver;
Elements elements;
public RecordEditPage(WebDriver driver) {
this.driver = driver;
}
public WebElement recordInfoSectionHeader() {
WebElement element = driver.findElement(By.id("record-id_header"));
System.out.println("Printing the element's text " + element.getText());
return element;
}
public void waitToLoad() throws Exception{
System.out.println("Printing the element's text " + this.recordInfoSectionHeader().getText()); \\This is printing the text properly
elements.waitToBePresentInDom(driver, this.recordInfoSectionHeader(), 25);
}
}
元素类
public class Elements {
public void waitToBePresentInDom(WebDriver driver, WebElement element, int secondsDelay) throws Exception {
try {
WebDriverWait wait = new WebDriverWait(driver, secondsDelay);
wait.until(ExpectedConditions.visibilityOf(element) );
} catch (Exception e) {
if ((ExceptionUtils.indexOfThrowable(e, TimeoutException.class) != -1)
|| (ExceptionUtils.indexOfThrowable(e, NoSuchElementException.class) != -1)) {
e = new Exception(element + " failed to appear!!!\n\n");
}
throw e;
}
}
}
我遇到的错误:
java.lang.NullPointerException: Cannot invoke "com.utilities.Elements.waitToBePresentInDom(org.openqa.selenium.WebDriver, org.openqa.selenium.WebElement, int)" because "this.element" is null
更新 当我将 waitToBePresentInDom() 函数移到我的页面对象时,它运行良好。但是,我不想将 waitToBePresentInDom() 保留在我的页面对象类中,而是保留在一个单独的类中,以便所有页面对象都可以使用 waitToBePresentInDom()。
【问题讨论】: