如何基于标签条件单命令执行Cucumber测试:@Smoke通过才跑@Regression
实现方案
完全可以实现,下面提供两种实用方案满足你的需求:
方案一:使用Shell/Batch脚本(推荐,简单直接)
通过脚本先执行Smoke测试,根据命令退出码判断是否继续执行Regression测试(Maven测试失败时会返回非0退出码)。
Linux/macOS Shell脚本
创建run-tests.sh文件,内容如下:
#!/bin/bash # 执行@Smoke标签测试 echo "开始执行Smoke测试..." mvn test -Dcucumber.options="--tags @Smoke" # 检查测试结果,0表示成功 if [ $? -eq 0 ]; then echo "Smoke测试通过,启动Regression测试..." mvn test -Dcucumber.options="--tags @Regression" else echo "Smoke测试失败,终止流程" exit 1 fi
赋予脚本执行权限:chmod +x run-tests.sh,运行时直接执行./run-tests.sh。
Windows Batch脚本
创建run-tests.bat文件,内容如下:
@echo off echo 开始执行Smoke测试... mvn test -Dcucumber.options="--tags @Smoke" :: 检查退出码,0为测试成功 if %errorlevel% equ 0 ( echo Smoke测试通过,启动Regression测试... mvn test -Dcucumber.options="--tags @Regression" ) else ( echo Smoke测试失败,终止流程 exit /b 1 )
直接双击脚本或在命令行执行run-tests.bat即可。
方案二:通过Maven配置实现(无需额外脚本)
在项目的pom.xml中配置Maven Surefire插件,分阶段执行测试,利用Maven的生命周期特性,当Smoke测试失败时自动终止后续流程。
修改pom.xml的build节点:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.1.2</version> <executions> <!-- 第一阶段:执行Smoke测试 --> <execution> <id>run-smoke-tests</id> <phase>test</phase> <goals> <goal>test</goal> </goals> <configuration> <systemPropertyVariables> <cucumber.options>--tags @Smoke</cucumber.options> </systemPropertyVariables> </configuration> </execution> <!-- 第二阶段:仅当Smoke测试通过时执行Regression测试 --> <execution> <id>run-regression-tests</id> <phase>post-integration-test</phase> <goals> <goal>test</goal> </goals> <configuration> <systemPropertyVariables> <cucumber.options>--tags @Regression</cucumber.options> </systemPropertyVariables> </configuration> </execution> </executions> </plugin> </plugins> </build>
配置完成后,只需运行Maven命令:
mvn verify
- Maven会先执行
test阶段的Smoke测试,若失败则直接终止,不会进入后续阶段 - 若Smoke测试通过,会继续执行
post-integration-test阶段的Regression测试
注意事项
- 确保你的Cucumber测试Runner类能正确识别
cucumber.options参数 - 若使用JUnit5,需确保Surefire插件版本支持JUnit5,或改用
maven-failsafe-plugin(适用于集成测试场景) - 测试失败时,Maven默认会返回非0退出码,这是脚本和Maven配置判断的核心依据
内容的提问来源于stack exchange,提问作者Sailesh Botcha
相关产品推荐
相关产品推荐

