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

Selenium-Maven-Cucumber框架NullPointerException问题求助

问题分析与解决方案

1. 空指针异常(NullPointerException)原因与修复

你的End2EndSteps类中仅声明了BaseClass bS;但从未初始化该对象,调用bS.openChromeBrowser()时必然触发空指针异常。同时,openChromeBrowser方法返回的WebDriver实例未赋值给类中的driver变量,后续操作会持续使用null的驱动实例。

修复代码(End2EndSteps):

public class End2EndSteps {

    public WebDriver driver;
    BaseClass bS;

    @Given("User is on Home Page")
    public void user_is_on_home_page() {
        // 初始化BaseClass实例
        bS = new BaseClass();
        // 将返回的WebDriver实例赋值给类变量
        driver = bS.openChromeBrowser(driver);
        // 打开目标应用URL
        driver.get(bS.getApplicationUrl());
    }
}

2. 潜在StackOverflowError原因与修复

你提到实例化BaseClass时出现栈溢出,结合当前代码看,核心问题在setBrowserProperties方法的不合理实现:

  • 方法声明返回String,但System.setProperty仅返回属性的旧值(可能为null),且重复调用getDriverPath()做冗余检查;
  • openChromeBrowser中连续两次调用setBrowserProperties(),属于无意义的重复操作。

修复代码(BaseClass):

// 修改为void类型,无需返回值
private void setBrowserProperties(){
    String driverPath = getDriverPath();
    System.setProperty("webdriver.chrome.driver", driverPath);
}

public WebDriver openChromeBrowser(WebDriver driver){
    setBrowserProperties();
    driver = new ChromeDriver();
    // 直接设置隐式等待,简化后续操作
    driver.manage().timeouts().implicitlyWait(getImplicitlyWait(), java.util.concurrent.TimeUnit.SECONDS);
    return driver;
}

3. 配置文件格式错误

你的Configuration.properties中值带有双引号,会导致读取到的URL、driverPath包含多余引号,引发后续路径或访问错误:

# 错误写法
url="https://shop.demoqa.com"
driverPath="C:\mine\Automation_JARS_Drivers\chromedriver\chromedriver.exe"

# 正确写法(去掉引号,Windows路径用双反斜杠转义)
url=https://shop.demoqa.com
driverPath=C:\\mine\\Automation_JARS_Drivers\\chromedriver\\chromedriver.exe
# 或使用正斜杠避免转义
# driverPath=C:/mine/Automation_JARS_Drivers/chromedriver/chromedriver.exe

其他优化建议

  • 用try-with-resources简化BaseClass构造函数的流操作,确保资源自动关闭:
public BaseClass(){
    try (BufferedReader reader = new BufferedReader(new FileReader(propertyFilePath))) {
        properties = new Properties();
        properties.load(reader);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        throw new RuntimeException("Configuration.properties not found at " + propertyFilePath);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException("Failed to load configuration properties", e);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 12:57:16