创建新对象行时出现 java.lang.NullPointerException

标签 java selenium testing

我正在尝试使用 TestNG 和页面对象进行我的 Selenium 测试。但在我创建页面对象类的新对象的那一行,它因 java.lang.NullPointerException 错误而失败。

public class TestTitle {

    @Test
    public void scenario1() {

        System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
        WebDriver driver=new ChromeDriver();
        FirstPage fp = new FirstPage(driver);
        driver.get("https://www.google.com/");
        fp.element.click();
    }
}


public class FirstPage {

    WebDriver driver;
    public FirstPage (WebDriver driver) {
        this.driver = driver;
    }

    public WebElement element = driver.findElement(By.id("hptl"));

}




FAILED: scenario1
java.lang.NullPointerException
at Pages.FirstPage.<init>(FirstPage.java:14)
at Test.TestTitle.scenario1(TestTitle.java:15)

FirstPage.java:14 是 public WebElement element = driver.findElement(By.id("hptl")); TestTitle.java:15 是 FirstPage fp = new FirstPage(driver);

最佳答案

试试这个

public class FirstPage {

    public WebDriver driver;
    public WebElement element;

    public FirstPage (WebDriver driver) {
        this.driver = driver;
        this.element = driver.findElement(By.id("hptl"));
    }

}

关于创建新对象行时出现 java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57665914/

相关文章:

java - 在 main 方法中启动手动线程

selenium - 通过 marionette 驱动程序在 Firefox 浏览器中设置代理

java - 如何使用java单击链接时打开新窗口

testing - Ubuntu 18 自动完成错误? "bash: cd: too many arguments"

java - 如何使用 java 以编程方式创建 odt 文件?

java - Android:将 Extras (ArrayList) 发送到任何 Activity

json - openjdk-1.8.0 中无法使用 JSONObject 和 JSONException

python-3.x - 如何从 Python Selenium 中的类中提取所有 href?

java - 为什么不能同时使用 Mock 和 InjectMocks?

Android:仅为测试添加单独的资源