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

如何在Serenity Cucumber Java中获取总时长、测试用例通过/失败数

获取Serenity + Cucumber测试的时长、通过/失败用例数的方法

一、直接查看Serenity生成的HTML报告(最简便)

Serenity默认会在target/site/serenity目录生成详细的HTML报告,核心数据直接可见:

  • 测试总时长:报告顶部的Duration字段会显示整体测试耗时
  • 通过/失败用例数:报告首页的统计面板会明确列出Passed、Failed、Pending等状态的用例数量,以及总用例数

二、通过代码在测试运行时获取统计数据

1. 结合Cucumber Hook与Serenity API

利用Cucumber的@AfterAll钩子,搭配Serenity内置的测试结果API,可以在测试结束时直接输出统计信息:

import net.serenitybdd.core.Serenity;
import net.serenitybdd.model.domain.TestOutcome;
import net.serenitybdd.model.domain.TestResult;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.extension.ExtendWith;
import net.serenitybdd.junit5.extension.SerenityJUnit5Extension;
import java.util.List;

@ExtendWith(SerenityJUnit5Extension.class)
public class TestStatisticsCollector {

    @AfterAll
    public static void collectTestStats() {
        // 获取所有测试用例的执行结果
        List<TestOutcome> allOutcomes = Serenity.getTestOutcomes();
        
        // 计算总时长(毫秒转秒)
        long totalDurationMs = allOutcomes.stream()
                .mapToLong(TestOutcome::getDurationInMillis)
                .sum();
        double totalDurationSec = totalDurationMs / 1000.0;
        
        // 统计各状态用例数
        long passedCount = allOutcomes.stream()
                .filter(outcome -> outcome.getStatus() == TestResult.SUCCESS)
                .count();
        long failedCount = allOutcomes.stream()
                .filter(outcome -> outcome.getStatus() == TestResult.FAILURE)
                .count();
        long totalCaseCount = allOutcomes.size();
        
        // 输出统计结果
        System.out.println("===== 测试统计 =====");
        System.out.println("总测试时长: " + totalDurationSec + " 秒");
        System.out.println("总用例数: " + totalCaseCount);
        System.out.println("通过用例数: " + passedCount);
        System.out.println("失败用例数: " + failedCount);
    }
}

注意:需要确保项目引入了Serenity核心依赖,且测试类使用Serenity的JUnit扩展。

2. 解析Serenity的JSON报告文件

Serenity会同步生成JSON格式的汇总报告(默认路径:target/site/serenity/serenity-summary.json),可以通过读取该文件解析数据:

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;

public class SerenityJsonParser {
    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        // 映射JSON结构到实体类
        SerenityTestSummary summary = mapper.readValue(
                new File("target/site/serenity/serenity-summary.json"),
                SerenityTestSummary.class
        );
        
        // 提取统计数据
        double totalDuration = summary.getDuration();
        TestStats stats = summary.getStats();
        
        System.out.println("总测试时长: " + totalDuration + " 秒");
        System.out.println("总用例数: " + stats.getTotal());
        System.out.println("通过用例数: " + stats.getPassed());
        System.out.println("失败用例数: " + stats.getFailed());
    }
    
    // 对应JSON结构的实体类
    static class SerenityTestSummary {
        private double duration;
        private TestStats stats;
        
        // Getter & Setter
        public double getDuration() { return duration; }
        public void setDuration(double duration) { this.duration = duration; }
        public TestStats getStats() { return stats; }
        public void setStats(TestStats stats) { this.stats = stats; }
    }
    
    static class TestStats {
        private long total;
        private long passed;
        private long failed;
        
        // Getter & Setter
        public long getTotal() { return total; }
        public void setTotal(long total) { this.total = total; }
        public long getPassed() { return passed; }
        public void setPassed(long passed) { this.passed = passed; }
        public long getFailed() { return failed; }
        public void setFailed(long failed) { this.failed = failed; }
    }
}

这种方式适合测试完成后,通过外部脚本或程序批量获取统计数据。

三、通过构建工具命令行输出

如果使用Maven运行测试,可在pom.xml中配置Serenity插件,让控制台直接输出简要统计:

<plugin>
    <groupId>net.serenity-bdd.maven.plugins</groupId>
    <artifactId>serenity-maven-plugin</artifactId>
    <version>3.9.2</version>
    <executions>
        <execution>
            <id>generate-serenity-reports</id>
            <phase>post-integration-test</phase>
            <goals>
                <goal>aggregate</goal>
            </goals>
        </execution>
    </executions>
</plugin>

运行mvn verify后,控制台会输出类似如下的统计信息:

[INFO] Test Results:
[INFO] 
[INFO] Total tests run: 15, Failures: 2, Errors: 0, Skipped: 1
[INFO] Total time: 45.6 seconds

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 00:12:49