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

如何在Cucumber JVM6的After钩子中提取Scenario Outline的Examples值

在Cucumber JVM6的After钩子中获取Scenario Outline的Examples数据

实现方案

由于Cucumber JVM6的Scenario接口没有直接提供获取Examples的方法,可通过其内部API实现需求,无需新增StepDef或技术步骤:

代码实现

import io.cucumber.java.After;
import io.cucumber.java.Scenario;
import io.cucumber.core.backend.TestCaseState;
import io.cucumber.core.gherkin.Pickle;
import io.cucumber.core.runner.TestCase;
import java.util.List;
import java.util.Map;

public class ReportHooks {

    @After
    public void extractExamplesData(Scenario scenario) {
        // 转换为TestCaseState获取内部测试用例对象
        TestCaseState testCaseState = (TestCaseState) scenario;
        TestCase testCase = testCaseState.getTestCase();

        // 获取当前执行的Pickle(对应Scenario Outline展开后的单条用例)
        Pickle currentPickle = testCase.getPickle();

        // 从Scenario Outline中提取Examples数据
        testCase.getScenarioOutline().ifPresent(outline -> {
            outline.getExamplesList().forEach(examples -> {
                // 获取Examples表头
                List<String> headers = examples.getTableHeader().getCells();
                // 获取Examples所有数据行
                List<List<String>> dataRows = examples.getTableBody().getCells();

                // 处理数据:比如输出到报告、存储等
                System.out.println("Examples表头:" + headers);
                dataRows.forEach(row -> System.out.println("Examples数据行:" + row));

                // 获取当前用例使用的参数(匹配Examples中的具体行)
                Map<String, String> currentParams = currentPickle.getParameters();
                System.out.println("当前执行场景的参数:" + currentParams);
            });
        });
    }
}

关键说明

  • 内部API依赖:通过TestCaseState(Scenario的内部实现接口)获取TestCase,进而访问ScenarioOutline和Examples数据。
  • 数据匹配:currentPickle.getParameters()返回当前执行场景对应的参数键值对(如{catName=Fluffy}),可用于定位该场景在Examples中的对应行。
  • 兼容性:该方案基于Cucumber JVM6的内部API,版本兼容性需与JVM6保持一致,后续版本升级时需验证API是否变更。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 09:41:12