如何让钩子在带有特定标签的每个步骤之后执行?

问题描述 投票:0回答:1

我想设置一个仅在断言步骤(我用 @Then 标记标记的步骤)之后运行的后步骤挂钩。 这可能吗? 我正在努力

    @AfterStep(value = "@Then")
public void afterStep(Scenario scenario) {
    try {
        takeScreenshot(scenario);
    }
    catch (IllegalStateException ignore){
    }
}

但是它仅在场景标记有 @Then 时运行,它不会查看步骤标签。 欢迎任何帮助! 谢谢!

java tags cucumber cucumber-java
1个回答
0
投票

我担心这不可能开箱即用。

Cucumber 没有提供明确的 API 来访问 @BeforeStep/@AfterStep 挂钩中当前运行的步骤。

总的来说,我看到了两种可能的选择来实现所需的目标(不使用黄瓜对象的反射,其状态无法保证):

  • 最简单的就是步骤实现中截图。您可能有一个驱动程序在您的步骤中传递,场景也可以移动到某个共享上下文,因此您可以创建一种奇特的屏幕截图方法。此选项很容易实现,但会导致少量但仍然是代码重复。喜欢:


    public void stepImpl() {
        try {
            // some step logic
            driver.....
        } finally {
            takeScreenshot(driver, context.getScenario());
        }
    }

  • 您可以尝试使用aspectj。设置起来可能有点复杂,但是使用aspectj(以及一般的AOP),您可以创建只能应用于那些用cucumber的@Then注释注释的方法的建议。但在这种情况下,您还需要将驱动程序和场景存储在某些共享上下文中,以便能够在您的方面使用它。喜欢:


    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.Around;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Pointcut;
    
    @Aspect
    public class ScreenshottingAspect {
    
        @Pointcut("execution(* your.package..*(..)) && @annotation(io.cucumber.java.en.Then)")
        public void methodExecution() {
        }
    
        @Around("methodExecution()")
        public Object captureScreenshot(ProceedingJoinPoint joinPoint) throws Throwable {
            try {
                return joinPoint.proceed();
            } finally {
                takeScreenshot(context.getDriver(), context.getScenario());
            }
        }
    
    }


© www.soinside.com 2019 - 2024. All rights reserved.