PHPUnit SpeedTrap

Packages

March 1st, 2019

phpunit-speedtrap.jpg

PHPUnit Speedtrap is a package by John Kary that reports on slow-running tests in your PHPUnit test suite. This package is inspired by Ruby RSpec’s --profile option that displays feedback about slow tests:

SpeedTrap reports on slow-running PHPUnit tests right in the console.

Many factors affect test execution time. A test not properly isolated from variable latency (database, network, etc.) and even basic load on the test machine will cause test execution times to fluctuate.

From the project’s readme, here’s an example of what you can expect:

I am not super familiar with tapping into PHPUnit, so I enjoyed diving into the package’s source code and learning how PHPUnit listeners work. In a phpunit.xml file you can enable this package with the following XML:

1<listeners>
2 <listener class="JohnKary\PHPUnit\Listener\SpeedTrapListener" />
3</listeners>

A more extensive example includes customizable options for defining the “slowTreshold” and “reportLength”. You can customize what your test suite considers a “slow” test defined in milliseconds:

1<listeners>
2 <listener class="JohnKary\PHPUnit\Listener\SpeedTrapListener">
3 <arguments>
4 <array>
5 <element key="slowThreshold">
6 <integer>500</integer>
7 </element>
8 <element key="reportLength">
9 <integer>5</integer>
10 </element>
11 </array>
12 </arguments>
13 </listener>
14</listeners>

Along with the listener, the package demonstrates using an annotation to override these configuration options on the per-test level:

1/**
2 * @slowThreshold 5000
3 */
4public function testLongRunningProcess()
5{
6 // Code that takes a longer time to execute
7}

You can learn more about the PHPUnit Speedtrap package at johnkary/phpunit-speedtrap and also check out these tips on speeding up your PHPUnit tests

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.