Cucumber 6.10.2+与Surefire并行测试异常求助:WebDriver会话泄露
解决Cucumber 6+ 并行测试WebDriver会话泄露问题
核心原因
Cucumber 6.10.2及以上版本调整了Spring上下文的初始化策略,默认复用上下文实例;而JUnit 4 + Surefire 3.0.0.M3+的并行机制会让单例Bean(如WebDriver)被多线程共享,最终引发会话泄露。Cucumber 4.8.1采用每个场景独立创建上下文的策略,因此无此问题。
解决方案
1. 配置WebDriver为线程安全Bean
将WebDriver的作用域设为thread,确保每个线程拥有独立实例:
@Configuration public class WebDriverConfiguration { // 注册线程作用域 @Bean public static CustomScopeConfigurer threadScopeConfigurer() { CustomScopeConfigurer configurer = new CustomScopeConfigurer(); Map<String, Object> scopes = new HashMap<>(); scopes.put("thread", new ThreadScope()); configurer.setScopes(scopes); return configurer; } // 线程安全的WebDriver实例 @Bean @Scope("thread") public WebDriver webDriver() { ChromeOptions options = new ChromeOptions(); options.addArguments("--headless=new"); // 可根据需求添加浏览器配置 return new ChromeDriver(options); } }
注意:所有依赖WebDriver的步骤类必须通过Spring注入获取实例,禁止用static变量存储。
2. 调整Surefire插件配置(JUnit 4环境)
通过forkCount和reuseForks参数让每个测试线程运行在独立JVM进程,避免类加载共享:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0.M7</version> <configuration> <parallel>classes</parallel> <threadCount>4</threadCount> <forkCount>1C</forkCount> <!-- 按CPU核心数分配fork进程 --> <reuseForks>false</reuseForks> <!-- 不复用进程,确保隔离 --> </configuration> </plugin>
3. JUnit 5(Jupiter)环境适配方案
若采用Spring Boot 2.6.2 + JUnit 5组合,需调整依赖与配置:
- 替换依赖:
<dependency> <groupId>io.cucumber</groupId> <artifactId>cucumber-junit-platform-engine</artifactId> <version>6.10.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-suite</artifactId> <version>1.8.2</version> <scope>test</scope> </dependency>
- 配置JUnit Platform并行策略,在
src/test/resources/junit-platform.properties中添加:
junit.jupiter.execution.parallel.enabled=true junit.jupiter.execution.parallel.mode.default=concurrent junit.jupiter.execution.parallel.config.strategy=fixed junit.jupiter.execution.parallel.config.fixed.parallelism=4
- 适配Surefire插件:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0.M7</version> <dependencies> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-surefire-provider</artifactId> <version>1.8.2</version> </dependency> </dependencies> </plugin>
4. 禁用Cucumber上下文复用(可选)
若上述方案无效,可强制每个场景创建新Spring上下文:
@CucumberContextConfiguration @SpringBootTest public class CucumberSpringConfig { @Autowired private ApplicationContext applicationContext; @Before public void resetContext() { ((ConfigurableApplicationContext) applicationContext).close(); } }
内容的提问来源于stack exchange,提问作者Susnigdha Chatterjee
相关产品推荐
相关产品推荐

