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

如何配置Maven默认不执行Cucumber测试,按需运行指定标签测试

解决方案:Cucumber默认不执行+标签控制测试执行

一、实现默认不执行Cucumber测试

JUnit5的@Suite类会被Maven Surefire插件默认扫描执行,要让mvn clean install test默认跳过Cucumber测试,有两种可行配置方式:

1. 通过Surefire插件排除测试类

在pom.xml中配置Surefire插件,默认排除Cucumber测试套件类,需要执行时通过命令行指定该类:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M7</version> <!-- 选择与JUnit5兼容的版本 -->
            <configuration>
                <!-- 默认跳过Cucumber测试套件 -->
                <excludes>
                    <exclude>**/RunCucumber.java</exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>
</build>

执行Cucumber测试时,通过命令行指定测试类+标签:

# 仅运行标记为@web的Cucumber测试
mvn clean install test -Dtest=RunCucumber -Dcucumber.filter.tags="@web"

2. 用自定义测试组控制

给Cucumber测试套件添加JUnit5的@Tag,让Surefire默认排除该组:
修改RunCucumber.java:

@Suite
@IncludeEngines("cucumber")
@SelectClasspathResource("features")
@ConfigurationParameters({
    @ConfigurationParameter(key = GLUE_PROPERTY_NAME, value = "com.petshop.store.cucumber.steps"),
})
@Tag("cucumber") // 标记自定义测试组
public class RunCucumber {
}

配置Surefire插件默认排除该组:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>3.0.0-M7</version>
    <configuration>
        <!-- 默认跳过cucumber组的测试 -->
        <excludedGroups>cucumber</excludedGroups>
    </configuration>
</plugin>

执行Cucumber测试时,指定组+标签:

mvn clean install test -Dgroups="cucumber" -Dcucumber.filter.tags="@web"

二、修复标签不生效问题

你之前配置的@ExcludeTags和硬编码的FILTER_TAGS_PROPERTY_NAME不生效,原因如下:

  • @ExcludeTags是JUnit5 Suite的注解,Cucumber不识别该注解,仅支持自身的标签过滤参数
  • 硬编码的标签规则会被命令行参数覆盖,且灵活性差

正确做法是移除代码中的硬编码标签配置,完全通过命令行参数动态控制:

  1. 删除RunCucumber.java中的@ExcludeTags和FILTER_TAGS_PROPERTY_NAME配置项
  2. 通过-Dcucumber.filter.tags参数控制测试执行:
# 仅运行@web标签的测试
mvn clean install test -Dtest=RunCucumber -Dcucumber.filter.tags="@web"

# 排除@web标签的测试(运行其他标签)
mvn clean install test -Dtest=RunCucumber -Dcucumber.filter.tags="!@web"

同时确保feature文件中的标签格式正确,例如:

@web
Feature: 网页端订单流程
  Scenario: 用户创建订单
    Given 用户进入商品详情页
    When 选择商品并提交订单
    Then 订单状态显示为待支付

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 06:08:26