When working with Maven projects, the Surefire plugin is commonly used to execute tests, but it lacks a built-in feature to display the total execution time across all test suites. This can be particularly important when monitoring performance trends in larger projects with many test classes.
Maven’s Surefire plugin reports execution time for individual test classes but doesn’t provide an aggregated view of the total test execution time. The reports are generated in the “target/surefire-reports” folder, both as text files and XML files.
Here’s a shell script that parses the XML report files generated by Surefire and calculates the total execution time. The script is compatible with both Linux and macOS environments.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#!/bin/bash # Calculate total test execution time by summing only the time attributes from the testsuite elements # Using a more compatible awk syntax for macOS and other platforms echo -e "\n========================================" echo "TOTAL SUREFIRE EXECUTION TIME: $(awk ' /<testsuite/ { for (i=1; i<=NF; i++) { if ($i ~ /^time=/) { gsub(/time="/, "", $i); gsub(/".*/, "", $i); total += $i; } } } END { printf "%.3f seconds", total }' target/surefire-reports/TEST-*.xml)" echo "========================================" |
These are the steps:
- Look for lines containing
<testsuite>
tags - For each matching line, loops through all fields (words) in the line
- Find fields that start with
time=
- Uses
gsub()
to extract just the numeric value by removing thetime="
prefix and the"
suffix - Add the extracted value to the running total
- Format the output in the same way, with the total time in seconds
To make this script run automatically after your tests, you can integrate it into your Maven build process using the exec-maven-plugin
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>3.5.0</version> <executions> <execution> <id>extract-total-test-time</id> <phase>test</phase> <goals> <goal>exec</goal> </goals> <configuration> <executable>bash</executable> <arguments> <argument>report-total-time.sh</argument> </arguments> </configuration> </execution> </executions> </plugin> |
The above snippet assumes the script is in a file “report-total-time.sh” in the same directory as the POM. Otherwise, you’ll have to adjust the argument accordingly.
When your tests complete, you’ll see output similar to:
1 2 3 |
======================================== TOTAL SUREFIRE EXECUTION TIME: 4.237 seconds ======================================== |
That’s all!