Programmatically Find Tests With PHPUnit

Nothing annoys me more than having to manually add tests to a central location in order to get them to run. Here’s some code that automatically and recursively (down the directory tree) finds files ending in Test.php and loads the tests within. Now all you need to do is create the tests.

< ?php

require_once 'PHPUnit/Framework.php';
require_once 'PHPUnit/TextUI/TestRunner.php';

define(Test, '/path/to/test/dir');

class AllTests {
    public static function main() {
        PHPUnit_TextUI_TestRunner::run(self::suite());
    }

    public static function suite() {
        $suite = new PHPUnit_Framework_TestSuite('My Test Suite');
        foreach (self::find_all_tests(TEST) as $path) {
            require_once($path);
            $class = preg_replace('%.*/(.*)\.php%', '$1', $path);
            $suite->addTestSuite($class);
        }
        return $suite;
    }

    private static function find_all_tests($start_dir) {
        $res = array();
        foreach (glob("$start_dir/*Test.php") as $path) {
            $res[] = $path;
        }
        foreach (glob($start_dir . '/*', GLOB_ONLYDIR) as $subdir) {
            $res = array_merge($res, self::find_all_tests($subdir));
        }
        return $res;
    }
}

?>

Leave a Reply

Your email address will not be published.