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

如何在Cucumber Extent Report对应步骤节点中记录方法数据?

问题:如何将Extent Report日志关联到对应测试步骤节点内

现有代码

Login.java 中的方法

public void addMakerUserNameInputField() {
        System.out.println("Adding user name input field.");
        driver.findElement(usernameInputField).sendKeys(correctMaker1Username);
        Hook.logInfo("User name:: " + correctMaker1Username);
    }

public void addMakerPasswordInputField() {
        System.out.println("Adding password input field.");
        driver.findElement(passwordInputField).sendKeys(correctMaker1Password);
        Hook.logInfo("Password:: " + correctMaker1Password);
    }

Hook.java 中的代码

@AfterStep
public static void addingReportInfo(Scenario scenario) throws IOException {
        stepTestIndex += 1;
        if (!scenario.isFailed()) {
            test.createNode(StepDetails.stepName)
                    .log(Status.PASS, "Test step passed.");
        }
}

public static void logInfo(String message) {
        if (test != null) {
            test.log(Status.INFO, message);
        }
    }

问题描述

当前Cucumber HTML Extent Report中,User name:: correctMaker1Username和Password:: correctMaker1Password这类日志会显示在所有测试步骤的顶部,我希望把它们放到对应的步骤节点内,而非顶部。另外我不想使用Datatable,因为测试数据存在Excel文件中。

解决方案

可以实现,核心是让日志关联到当前步骤的节点而非全局测试对象,具体修改如下:

  1. 在Hook类中新增一个静态变量,用于存储当前执行的步骤节点:
private static ExtentTest currentStepNode;
  1. 修改@AfterStep方法,创建步骤节点时将其赋值给currentStepNode,同时覆盖失败场景的处理(可选):
@AfterStep
public static void addingReportInfo(Scenario scenario) throws IOException {
    stepTestIndex += 1;
    // 创建当前步骤的节点并保存
    currentStepNode = test.createNode(StepDetails.stepName);
    
    if (!scenario.isFailed()) {
        currentStepNode.log(Status.PASS, "Test step passed.");
    } else {
        // 可选:添加失败步骤的日志
        currentStepNode.log(Status.FAIL, "Test step failed: " + scenario.getError());
    }
}
  1. 修改logInfo方法,使用currentStepNode打印日志,而非全局的test对象:
public static void logInfo(String message) {
    if (currentStepNode != null) {
        currentStepNode.log(Status.INFO, message);
    }
}

补充说明

  • 可以在@BeforeStep注解的方法中添加currentStepNode = null;,确保每个步骤开始前清空节点引用,避免日志串到错误的步骤里。
  • 修改后,Login.java中调用Hook.logInfo时,日志会自动关联到当前执行的步骤节点内,不再显示在所有步骤顶部。

内容的提问来源于stack exchange,提问作者Thinn Wutt Hmone

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 19:22:52