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

如何通过AOP将截图附件嵌入Allure报告@Captured注解方法步骤内?

解决Allure截图附件与目标方法步骤绑定的问题

你的核心问题是:切面中独立调用的截图操作会生成新的Allure步骤,而非附加到被@Captured标记的目标方法对应的步骤上。这是因为目标方法执行完成后,Allure的当前步骤上下文已切换回上一层,此时调用截图会创建新的独立步骤。

解决方案:直接将截图附加到目标方法对应的Allure步骤

利用Allure的Lifecycle API,可直接操作已存在的步骤,将截图作为附件添加到目标方法对应的步骤中,无需创建新步骤。修改后的切面代码如下:

@Aspect
public class ScreenshotAppenderAspect {

    @Pointcut("@annotation(com.annotations.Captured)")
    public void captured() {}

    @Around("captured()")
    public Object aroundStep(ProceedingJoinPoint point) throws Throwable {
        Object result;
        // 保存目标方法执行前的步骤栈,用于定位目标步骤
        Deque<StepResult> preExecutionSteps = new ArrayDeque<>(Allure.getLifecycle().getCurrentStep());
        
        try {
            result = point.proceed();
            
            // 找出目标方法执行过程中新增的步骤(即被@Captured标记的方法对应的Allure步骤)
            Deque<StepResult> currentSteps = Allure.getLifecycle().getCurrentStep();
            if (currentSteps.size() > preExecutionSteps.size()) {
                // 获取目标方法对应的步骤(假设目标方法自身是一个@Step,即新增的第一个步骤)
                StepResult targetStep = new ArrayList<>(currentSteps).get(preExecutionSteps.size());
                // 直接向该步骤添加截图附件
                Allure.getLifecycle().addAttachment(
                    "执行后截图",
                    "image/png",
                    "png",
                    captureScreenshot() // 替换为你的截图字节数组获取逻辑
                );
            }
            
            return result;
        } catch (Throwable e) {
            // 可选:方法执行异常时添加失败截图
            Allure.getLifecycle().addAttachment(
                "失败截图",
                "image/png",
                "png",
                captureScreenshot()
            );
            throw e;
        }
    }

    // 示例截图方法,根据你的测试框架(如Selenium、Playwright)实现
    private byte[] captureScreenshot() {
        // 以Selenium为例:
        // return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
        return new byte[0]; // 替换为实际逻辑
    }
}

关键说明

  1. Allure生命周期上下文:Allure通过Lifecycle管理线程内的步骤栈,getCurrentStep()返回当前线程的步骤栈。目标方法执行后,栈中新增的步骤即为该方法对应的Allure步骤(前提是目标方法被@Step标记,或内部通过Allure.step()创建了步骤)。
  2. 直接绑定附件:调用Allure.getLifecycle().addAttachment()时,Allure会自动将附件关联到当前活跃的步骤。通过步骤栈的变化定位到目标步骤后,即可实现截图与目标步骤的绑定。
  3. 异常场景适配:在catch块中添加失败截图,同样会绑定到目标方法的步骤中,便于排查问题。

注意事项

  • 确保被@Captured标记的方法本身是一个Allure步骤(即标记@Step注解,或内部通过Allure API创建步骤),否则无法定位到对应的步骤对象。
  • 如果目标方法内部包含多个Allure步骤,上述代码会将截图附加到目标方法执行期间新增的第一个步骤,可根据需求调整步骤定位逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 19:57:28