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

在BDD Selenium中使用WebDriverManager出现IllegalStateException的解决方法

问题分析与解决方案

一、修正代码中的变量覆盖问题

你的代码存在静态driver被局部变量覆盖的问题,会导致后续close方法和PageFactory初始化时使用未赋值的静态driver,引发空指针或初始化异常,修正后代码如下:

public static WebDriver driver;

public void openup() {
    // 直接将WebDriverManager创建的驱动赋值给静态driver,无需手动new EdgeDriver()
    driver = WebDriverManager.edgedriver().create();
    driver.get("https://www.ikea.com/ca/en/");
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
}

public void close () {
    // 增加非空判断,避免空指针,建议调用quit彻底关闭驱动进程
    if(driver != null) {
        driver.close();
        driver.quit();
    }
}

public DriverFactory (){
    // 确保构造函数执行时driver已完成初始化,或移至openup方法执行后调用
    PageFactory.initElements(driver,this);
}

二、解决Guice+CGLIB与Java 9+模块系统的兼容性问题

报错堆栈核心错误为InaccessibleObjectException: module java.base does not "opens java.lang" to unnamed module,原因是Serenity依赖的旧版Guice使用的CGLIB无法兼容Java 9+的模块系统限制,可通过以下两种方式解决:

1. 添加JVM启动参数

运行测试时添加以下JVM参数,开放模块访问权限:

--add-opens java.base/java.lang=ALL-UNNAMED
--add-opens java.base/java.lang.reflect=ALL-UNNAMED

若使用Maven运行,可在pom.xml的surefire插件中配置:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <configuration>
        <argLine>
            --add-opens java.base/java.lang=ALL-UNNAMED
            --add-opens java.base/java.lang.reflect=ALL-UNNAMED
        </argLine>
    </configuration>
</plugin>

2. 升级Serenity与相关依赖版本

旧版Serenity(Thucydides)依赖的Guice版本过老,不兼容Java 9+。升级至最新稳定版的Serenity BDD依赖(如3.x系列),新版本已修复模块系统兼容性问题;同时确保WebDriverManager使用最新稳定版(如5.x系列)。

三、额外检查点

  • 确认Java版本:若使用Java 17及以上版本,需保证Serenity、Guice、WebDriverManager等所有依赖均支持对应Java版本
  • 移除冗余代码:WebDriverManager已封装驱动的下载与初始化逻辑,无需手动调用new EdgeDriver()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 18:24:57