You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium+TestNG测试报NullPointerException:searchContext为空求助

问题根源与修复方案

错误原因

TestBase类中带有@BeforeMethod、@AfterMethod注解的方法为默认访问权限(无public修饰符),TestNG无法通过反射机制识别并执行这些方法,导致driver对象未被初始化。当创建LandingPage实例时传入的是null的driver,PageFactory.initElements(null, this)无法完成元素绑定,最终调用linkToStore.click()时触发空指针异常。

修复步骤

1. 修正TestBase的方法访问权限

将setupEach()和quit()方法改为public,确保TestNG能执行这些生命周期方法:

import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;

import java.time.Duration;

public class TestBase {
    public WebDriver driver;

    @BeforeTest
    public void setUpAll() {
        WebDriverManager.chromedriver().setup();
    }

    @BeforeMethod
    public void setupEach() {
        driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
        driver.get("http://przyklady.javastart.pl/jpetstore/");
    }

    @AfterMethod
    public void quit() {
        // 增加null判断,避免驱动已释放时调用方法报错
        if (driver != null) {
            // 仅需quit即可,quit会关闭所有窗口并终止驱动进程
            driver.quit();
        }
    }
}

2. 验证LandingPage逻辑

LandingPage的代码本身无问题,确保构造函数中正确调用PageFactory.initElements(driver, this)即可:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class LandingPage {

    @FindBy(linkText = "Enter the Store")
    private WebElement linkToStore;

    public LandingPage(WebDriver driver) {
        PageFactory.initElements(driver, this);
    }

    public void enterTheStore() {
        linkToStore.click();
    }
}

补充说明

  • TestNG对生命周期注解方法的访问权限有明确要求,必须为public,否则无法执行初始化/清理逻辑。
  • driver.close()仅关闭当前窗口,driver.quit()会终止整个驱动进程并关闭所有关联窗口,因此在测试结束时只需调用quit()即可,避免重复操作导致异常。

内容的提问来源于stack exchange,提问作者Hoxzy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 00:42:33