我的代码看起来如下:
家长班:
package TestPackageForStructure;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class PageElements {
WebDriver driver;
public PageElements(WebDriver driver) {
this.driver = driver;
}
WebElement searchBox = driver.findElement(By.xpath("//*[@id=\"APjFqb\"]"));
}
少儿班:
package TestPackageForStructure;
import io.qameta.allure.Step;
import org.openqa.selenium.WebDriver;
public class PageSteps extends PageElements {
public PageSteps(WebDriver driver) {
super(driver);
}
@Step
public void inputData(String text) {
searchBox.sendKeys("Hello");
}
测试班:
import TestPackageForStructure.PageSteps;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class TestStructure {
@Test
public void insertSomeData() throws InterruptedException {
WebDriver driver = new ChromeDriver();
PageSteps pageSteps = new PageSteps(driver);
driver.get("https://www.google.com/");
Thread.sleep(5000);
pageSteps.inputData("Hello World");
}
}
错误: java.lang.NullPointerException:无法调用“org.openqa.selenium.WebDriver.findElement(org.openqa.selenium.By)”,因为“this.driver”为空
简而言之,我通过在子构造函数中使用 super 关键字将 WebDriver 实例扔给父类,但驱动程序仍然为 null
我期望将驱动程序传递给父类,并创建一个没有任何偏差的 WebElement 实例(驱动程序不为空)
我相信这应该可以修复你的代码:
WebElement searchBox;
public PageElements(WebDriver driver) {
this.driver = driver;
searchBox = driver.findElement(By.xpath("//*[@id=\"APjFqb\"]"));
}
您遇到的问题是
driver
尚未按照您的方式设置。