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

如何让@AfterStep钩子仅在带@Then标签的步骤后执行?

如何让@AfterStep钩子仅在@Then步骤后执行

你之前的写法存在误区:@AfterStep(value = "@Then") 中的@Then是用来匹配标记了该标签的场景,而非单个@Then注解的步骤,所以只会在带有@Then标签的场景结束后触发,而不是每个@Then步骤之后。

要实现仅在@Then步骤后运行钩子,可以通过注入Step对象来判断当前步骤是否带有@Then注解,具体代码如下:

import io.cucumber.java.AfterStep;
import io.cucumber.java.Scenario;
import io.cucumber.java.en.Then;
import java.lang.annotation.Annotation;

@AfterStep
public void afterThenStep(Scenario scenario, io.cucumber.java.Step step) {
    // 遍历步骤的所有注解,检查是否包含@Then
    for (Annotation annotation : step.getAnnotations()) {
        if (annotation.annotationType() == Then.class) {
            try {
                takeScreenshot(scenario);
            } catch (IllegalStateException ignore) {
                // 忽略截图失败的异常
            }
            break;
        }
    }
}

代码说明

  1. 注入io.cucumber.java.Step对象,该对象包含当前执行步骤的元数据
  2. 通过step.getAnnotations()获取步骤上的所有注解,遍历判断是否存在@Then注解
  3. 若存在@Then注解,则执行你的截图逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 08:33:33