当试图将驱动程序初始化分离到单独的类时,我得到NullPointerException。我是Java的初学者,我哪里做错了?
BaseTest.java
package common;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import io.github.bonigarcia.wdm.WebDriverManager;
public class BaseTest {
public static WebDriver driver = null;
@BeforeSuite
public void launchBrowser() {
WebDriverManager.chromedriver().setup();
ChromeDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
@AfterSuite
public void closeBrowser() {
driver.close();
}
}
Test.java
package ui;
import org.testng.annotations.Test;
import common.BaseTest;
public class ListenerDemoTest extends BaseTest{
@Test
public void something() {
driver.get("https.//google.com");
}
}
错误信息:
java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebDriver.get(String)" because "ui.ListenerDemoTest.driver" is null
at ui.ListenerDemoTest.something(ListenerDemoTest.java:10)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
...
问题是你用空值初始化了驱动程序而没有在方法
中更新它更新BaseTest
public class BaseTest {
ChromeDriver driver;
@BeforeSuite
public void launchBrowser() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
@AfterSuite
public void closeBrowser() {
driver.close();
}
}
还有,你的URL中有一个错别字driver.get("https://google.com");
在BaseTest
中,您已经将WebDriver driver
实例初始化为null,但是您从未使用实际值更新引用,作为@BeforeSuite
设置的一部分。所以引用总是空的,导致NullPointerException异常。在@BeforeSuite
方法中,您已经完成了变量遮蔽,而不是更新driver
实例,您创建了名为driver
的本地实例,并且未能更新静态实例引用。
需要的更改是
@BeforeSuite
public void launchBrowser() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
}