Maven/Spring项目中JUnit与Selenium/Cucumber测试无法同时运行求助
解决Maven中JUnit 5与Cucumber测试无法同时运行的问题
问题背景
我有一个基于Spring Boot + Maven的测试项目,包含两类测试:
- JUnit 5(Jupiter)单元测试
- Cucumber + Selenium集成测试
在IntelliJ中单独运行两类测试都正常,但执行mvn test时出现异常:
- 使用surefire插件2.19.1版本时,仅Cucumber测试运行
- 升级到2.22.2版本后,仅JUnit 5测试运行
问题根源
- 依赖冲突:项目同时引入JUnit 4和JUnit 5依赖,导致surefire插件无法正确识别所有测试类型
- 插件版本适配:旧版本surefire对JUnit 5支持不完善,Cucumber 7.x虽兼容JUnit 5,但配置不当会导致测试类型互斥
- Cucumber运行器注解:使用JUnit 4的
@RunWith(Cucumber.class),在JUnit 5环境下与Jupiter测试存在兼容性冲突
解决方案步骤
1. 清理依赖,统一JUnit版本
移除pom.xml中单独的JUnit 4依赖,利用spring-boot-starter-test自带的JUnit Jupiter,同时替换Cucumber依赖为JUnit 5兼容版本:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <!-- 排除JUnit 4,彻底避免版本冲突 --> <exclusions> <exclusion> <groupId>junit</groupId> <artifactId>junit</artifactId> </exclusion> </exclusions> </dependency> <!-- Cucumber JUnit 5 适配依赖 --> <dependency> <groupId>io.cucumber</groupId> <artifactId>cucumber-java</artifactId> <scope>test</scope> <version>7.11.2</version> </dependency> <dependency> <groupId>io.cucumber</groupId> <artifactId>cucumber-junit-platform-engine</artifactId> <scope>test</scope> <version>7.11.2</version> </dependency> <!-- Selenium依赖添加test scope,避免污染主代码 --> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.17.0</version> <scope>test</scope> </dependency> </dependencies>
2. 升级surefire插件到兼容版本
使用支持JUnit 5的surefire插件(推荐3.2.2及以上),简化配置无需硬编码测试类:
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.2.2</version> <configuration> <includes> <include>**/*Tests.java</include> <include>**/*Test.java</include> </includes> </configuration> </plugin> </plugins> </build>
3. 修改Cucumber运行器为JUnit 5兼容模式
替换JUnit 4的@RunWith注解,改用Cucumber的JUnit 5注解:
package com.example.CucumberSelenium; import io.cucumber.junit.platform.engine.Cucumber; import org.springframework.boot.test.context.SpringBootTest; @Cucumber @SpringBootTest public class CucumberTestRunnerTest { }
同时在src/test/resources下创建junit-platform.properties文件,配置Cucumber参数:
cucumber.features=src/test/java/com/example/CucumberSelenium/resources/features cucumber.glue=com.example.CucumberSelenium.stepdefs
4. 验证测试运行
执行命令mvn clean test,此时JUnit 5测试和Cucumber测试会被同时执行。
额外注意事项
- 确保Spring Boot 3.2.4与Java 21的兼容性(当前配置已满足)
- GitHub Actions运行时需配置浏览器驱动(或使用Headless模式)
- 定期同步Cucumber、Selenium与Spring Boot的版本,避免新的兼容性问题
内容的提问来源于stack exchange,提问作者Sam Kar
相关产品推荐
相关产品推荐

