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

如何在Java Cucumber JUnit中正确运行多个标签?

在Cucumber JUnit中正确使用多标签运行测试

项目依赖

你的项目使用的Maven依赖如下:

<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>4.4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.github.bonigarcia/webdrivermanager -->
<dependency>
    <groupId>io.github.bonigarcia</groupId>
    <artifactId>webdrivermanager</artifactId>
    <version>5.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-java -->
<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-java</artifactId>
    <version>7.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-junit -->
<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-junit</artifactId>
    <version>7.9.0</version>
</dependency>

原代码问题

你在Runner类中使用了旧的标签语法:

@RunWith(Cucumber.class) 
@CucumberOptions(
    features = {"src/test/resources"}, 
    plugin = {"pretty", "html:target/cucumber-reports.html", "json:target/cucumber.json", "junit:target/junit-cucumber-reports/Cucumber-junit.xml", "com.aventstack.extentreports.cucumber.adapter.ExtentCucumberAdapter:"}, 
    glue = {"/"}, 
    tags = "@PW and @WM" 
)

Cucumber 7.x版本已废弃and/or这类旧关键字,改用标准逻辑运算符,因此会触发语法异常。

正确写法

根据需求选择对应的标签表达式:

  1. 运行同时包含@PW和@WM标签的用例(逻辑与)
@RunWith(Cucumber.class) 
@CucumberOptions(
    features = {"src/test/resources"}, 
    plugin = {"pretty", "html:target/cucumber-reports.html", "json:target/cucumber.json", "junit:target/junit-cucumber-reports/Cucumber-junit.xml", "com.aventstack.extentreports.cucumber.adapter.ExtentCucumberAdapter:"}, 
    glue = {"/"}, 
    tags = "@PW && @WM" 
)
  1. 运行包含@PW或@WM标签的用例(逻辑或)
tags = "@PW || @WM"
  1. 数组形式的标签配置
    数组元素之间默认是逻辑或关系,适合拆分复杂表达式:
  • 等价于逻辑或:
tags = {"@PW", "@WM"}
  • 包裹复杂逻辑与表达式:
tags = {"@PW && @WM"}

扩展说明

Cucumber 7.x支持更灵活的标签表达式,比如排除特定标签:

tags = "(@PW || @WM) && not @Ignore"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 18:32:28