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

Cucumber中@BeforeStep仅对应所属StepDef类执行的实现疑问

Cucumber @BeforeStep 注解的工作机制与自定义触发逻辑问题

我在使用Cucumber的@BeforeStep注解时,希望明确它的实际工作机制。我编写了两个步骤定义类SampleStepDef1和SampleStepDef2,代码如下:

public class SampleStepDef1 {

    @BeforeStep
    public void beforeStep() {
       System.out.println("Before Step -- SampleStepDef1");
    }

    @Given("just a gherkin step1 - app1")
    public void just_a_gherkin_step1_app1() {
       // 业务实现
    }
}

public class SampleStepDef2 {

    @BeforeStep
    public void beforeStep() {
       System.out.println("Before Step -- SampleStepDef2");
    }

    @Given("just another gherkin step1 - app2")
    public void just_a_gherkin_step2_app2() {
       // 业务实现
    }
}

对应的Gherkin场景代码如下:

Scenario: Try Epic HyperDrive
    Given just a gherkin step1 - app1
    And just a gherkin step2 - app1

实际执行时发现:即使场景没有调用SampleStepDef2中的任何步骤,两个类的@BeforeStep方法依然都会被执行。

我有以下需求和疑问:

  • 是否可以让@BeforeStep仅在所属类的步骤被执行时才触发,且不使用标签过滤的方式?
  • 想了解Cucumber设计@BeforeStep这种全局触发机制的原因,同时寻求相关说明或实现建议。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 01:00:48