Serenity+Cucumber自动化测试:点击登录后Selenium重启驱动问题求助
我来帮你排查这个Ubuntu 16.04 LTS下的Web自动化测试问题,结合你用的技术栈,大概率是WebDriver实例的生命周期管理或者Serenity与Spring的上下文集成出了问题——尤其是点击登录后触发新驱动实例的情况,通常和上下文隔离、驱动实例没有单例绑定有关。下面是具体的排查和解决步骤:
问题排查与解决方案
1. 确保WebDriver实例的单例绑定
Serenity默认会管理WebDriver实例,但和Spring结合时容易出现上下文冲突,导致重复创建驱动。你需要把WebDriver实例绑定到Cucumber的胶水上下文,保证整个测试会话只初始化一次:
- 编写WebDriver配置类,用
@Bean+@Scope("cucumber-glue")注解:
@Configuration public class WebDriverConfig { @Bean @Scope("cucumber-glue") public WebDriver webDriver() { WebDriverManager.chromedriver().setup(); ChromeOptions options = new ChromeOptions(); options.addArguments("--headless"); // Ubuntu下建议加无头模式,避免UI依赖问题 return new ChromeDriver(options); } }
- 所有Steps类必须通过Spring注入获取WebDriver,禁止手动
new ChromeDriver(),防止重复初始化。
2. 修正StepsContext的上下文配置
你的StepsContext如果用了Spring的上下文注解,要确保它和Cucumber/Serenity的上下文对齐:
- 检查
StepsContext的@ContextConfiguration是否正确加载了WebDriver配置类,并且不要重复初始化上下文:
@ContextConfiguration(classes = {WebDriverConfig.class}) public class StepsContext { @Autowired protected WebDriver webDriver; // 其他共享变量/方法 }
- 所有业务Steps类直接继承
StepsContext即可,不要在每个Steps类中单独配置上下文,避免触发多个Spring上下文实例。
3. 同步Serenity与Cucumber的生命周期
Serenity有自己的测试生命周期规则,和Cucumber结合时需要强制复用驱动实例:
- 在项目根目录的
serenity.properties中添加如下配置:
serenity.reuse.driver=true serenity.restart.between.scenarios=false serenity.driver.maximized=true serenity.timeout=10000
- 确认依赖版本兼容:Serenity 2.x搭配Cucumber 6.x、WebDriverManager 5.x是比较稳定的组合,版本不兼容会导致上下文混乱。
4. 修复登录步骤的等待逻辑
点击登录后出现问题,可能是页面跳转时等待不足,导致Serenity误以为会话失效而重启驱动:
- 替换
Thread.sleep(),用显式等待确认首页元素加载完成:
WebDriverWait wait = new WebDriverWait(webDriver, Duration.ofSeconds(10)); wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("homepage-main-element")));
- 检查登录按钮的定位器是否唯一,如果页面存在多个相同定位的元素,会导致点击无效,进而触发后续错误处理逻辑。
5. Ubuntu环境的依赖检查
Ubuntu 16.04上运行ChromeDriver可能缺失系统依赖,导致驱动崩溃后Serenity重启:
- 安装Chrome运行所需的依赖库:
sudo apt-get update && sudo apt-get install libnss3 libgconf-2-4 libxss1 libappindicator1 libindicator7
- 确认Chrome浏览器和ChromeDriver版本匹配(WebDriverManager会自动处理,但可以手动验证
chromedriver --version和Chrome版本是否一致)。
内容的提问来源于stack exchange,提问作者Bogdan
相关产品推荐
相关产品推荐

