有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

通过maven surefirereport在单个文件中以摘要格式在单元测试类中执行测试的java时间

有人能告诉我如何通过maven-surefire在单个文件中获得单元测试类中每个单元测试所花费的时间吗?我已经看到了我的target/surefire-report,它有每个测试的文件。基本上,我要找的是一个包含所有执行时间摘要的文件。如果可能,还可以根据每个测试的执行时间对结果进行排序

我使用的是maven 3.5&;MacOSX 10.12.6上的surefire插件2.4.2


共 (3) 个答案

  1. # 1 楼答案

    我用Martin Höller的片段编写了一个小的bash脚本,可能会对某人有所帮助:

    #!/bin/bash
    
    # This script goes through tests results in `target/surefire-reports` and sorts the results by the
    # amount of time they took. This is helpful to identify slow tests.
    
    set -e
    
    # Make sure the surefire folder exists
    if [ ! -d "target/surefire-reports" ]; then
        echo "The folder 'target/surefire-reports' doesn't exists. Please run tests before using this script."
        exit 1
    fi
    
    # Go through the surefire test reports and sort tests by time taken. Source for this snippet:
    # https://stackoverflow.com/questions/45854277/execution-time-of-tests-in-unit-test-class-via-maven-surefire-report-in-a-single/45859700#45859700
    grep -h testcase target/surefire-reports/TEST-*.xml |
        awk -F '"' '{print $4 "#" $2 "() - " $6 "ms" }' |
          sort -rn -k 3
    
  2. # 2 楼答案

    您可以使用surefire-report-plugin来聚合结果(但它仍然不会被排序)

    mvn surefire-report:report -DlinkXRef=false -Daggregate=true
    

    或者

    mvn surefire-report:report-only -DlinkXRef=false -Daggregate=true
    

    如果您已经使用surefire插件构建了项目

    这将生成surefire报告。html在根目标目录中,您可以在其中找到每个模块和每个测试套件的时间统计信息

  3. # 3 楼答案

    目前maven-surefire-plugin不允许您这样做。它将所有结果写入单独的文件中。如果你觉得这是一个缺少的特性,你可以在它的issue tracker中创建一个特性请求

    但是,您可以使用一些Linux命令将输出转换为所需。以下是一些命令,它们可以将单独的XML文件转换为一个看起来像您想要的文件:

    grep testcase target/surefire-reports/TEST-*.xml |
      sed 's/.* name="\(.*\)" classname="\(.*\)" time="\(.*\)".*/\2#\1() - \3ms/g' |
      sort -n -k 3 > output.txt
    

    更新:数字排序存在分数变化的问题 数字。使用下面的awk版本来解决这个问题


    同样的事情也可以在awk稍微短一点、不那么神秘的情况下完成:

    grep -h testcase target/surefire-reports/TEST-*.xml |
      awk -F '"' '{printf("%s#%s() - %.3fms\n", $4, $2, $6); }' |
      sort -n -k 3 > output.txt
    

    生成surefire报告后,必须从maven项目的顶层目录执行这些命令

    如果您有多模块项目,请使用以下选项:

    find . -name TEST-*.xml -exec grep -h testcase {} \; |
      awk -F '"' '{printf("%s#%s() - %.3fms\n", $4, $2, $6); }' |
      sort -n -k 3 > output.txt
    

    结果文件为output.txt,包含以下格式的行:

    <classname>#<methodname>() - <time>ms
    

    结果按消耗的时间排序