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

如何在Cucumber Before Hook中读取Example的标签名称

嘿,我来帮你搞定这个打印Examples标签的问题!你的思路已经找对方向了,只是代码里还有几个小地方需要调整才能正确输出@example_tag。

先确认你的Cucumber测试用例

@feature_tag
Feature: 功能描述
@outline_tag
Scenario Outline: 场景大纲描述
Given 场景详情
@example_tag
Examples:
|num_1 | num_2 | result |
| 1 | 1 | 2 |

完整可运行的Java代码调整方案

下面是修正后的代码,能准确获取并打印Examples上的@example_tag:

import cucumber.api.java.Before;
import cucumber.api.testng.PickleEventWrapper;
import cucumber.runtime.model.CucumberExamples;
import cucumber.runtime.model.CucumberScenarioOutline;
import gherkin.formatter.model.Tag;

import java.util.List;

@Before
public void beforeScenario(PickleEventWrapper eventWrapper) throws Exception {
    // 从PickleEvent中获取对应的Scenario Outline实例
    CucumberScenarioOutline scenarioOutline = (CucumberScenarioOutline) eventWrapper.getPickleEvent().getPickle().getScenarioOutline();
    
    if (scenarioOutline != null) {
        // 获取当前Scenario Outline下所有的Examples集合
        List<CucumberExamples> examplesList = scenarioOutline.getExamplesList();
        
        for (CucumberExamples examples : examplesList) {
            // 遍历Examples上的所有标签
            List<Tag> tags = examples.getTags();
            for (Tag tag : tags) {
                // 打印标签的完整名称,比如@example_tag
                System.out.println("Example Tags: " + tag.getName());
            }
        }
    }
}

几个关键调整说明

  • 改用PickleEventWrapper作为@Before方法的参数:这是Cucumber 4.x及以上版本中获取场景详情更可靠的方式
  • 使用Cucumber内部模型类:替换你原来的ScenarioOutline和Examples为CucumberScenarioOutline、CucumberExamples,这些是框架内部正确的类型
  • 直接获取完整标签名:通过tag.getName()可以拿到带@符号的完整标签字符串,正好符合你要打印@example_tag的需求

运行这段代码后,当执行到该Scenario Outline时,控制台就会输出你想要的Example Tags: @example_tag啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:31:04