Faster PHPUnit
I made a simple optimization to the test suite at OpenSky over the weekend and we are reaping big benefits. The premise is pretty straight forward. We use the setUp() method to create a lot of mock objects through our test suite. If these are allowed to accumulate they end up wasting a lot of space and slowing down your suite.
Luckily there is also a tearDown() method you can use to cleanup, and you can do it automatically if you use this base class:
<?php
abstract class BaseTestCase extends PHPUnit_Framework_TestCase
{
protected function tearDown()
{
foreach ($this->getTearDownProperties() as $prop) {
$prop->setValue($this, null);
}
parent::tearDown();
}
/**
* Returns an array of ReflectionProperty objects for tear down.
*/
private function getTearDownProperties()
{
static $cache = array();
$class = get_class($this);
if (!isset($cache[$class])) {
$cache[$class] = array();
$refl = new ReflectionClass($class);
$filter = ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED | ReflectionProperty::IS_PRIVATE;
foreach ($refl->getProperties($filter) as $prop) {
if (0 !== strpos($prop->getDeclaringClass()->getName(), 'PHPUnit_')) {
$prop->setAccessible(true);
$cache[$class][] = $prop;
}
}
}
return $cache[$class];
}
}
Our buddy Jenkins is much happier now — builds are approximately 20% faster.
