Autoloading classes in PHPUnit using Composer and autoload.php

Well, at first. You need to tell the autoloader where to find the php file for a class. That’s done by following the PSR-0 standard.

The best way is to use namespaces. The autoloader searches for a Acme/Tests/ReturningTest.php file when you requested a Acme\Tests\ReturningTest class. There are some great namespace tutorials out there, just search and read. Please note that namespacing is not something that came into PHP for autoloading, it’s something that can be used for autoloading.

Composer comes with a standard PSR-0 autoloader (the one in vendor/autoload.php). In your case you want to tell the autoloader to search for files in the lib directory. Then when you use ReturningTest it will look for /lib/ReturningTest.php.

Add this to your composer.json:

{
    ...
    "autoload": {
        "psr-0": { "": "lib/" }
    }
}

More information in the documentation.

Now the autoloader can find your classes you need to let PHPunit know there is a file to execute before running the tests: a bootstrap file. You can use the --bootstrap option to specify where the bootstrap file is located:

$ ./vendor/bin/phpunit tests --bootstrap vendor/autoload.php

However, it’s nicer to use a PHPunit configuration file:

<!-- /phpunit.xml.dist -->
<?xml version="1.0" encoding="utf-8" ?>
<phpunit bootstrap="./vendor/autoload.php">

    <testsuites>
        <testsuite name="The project's test suite">
            <directory>./tests</directory>
        </testsuite>
    </testsuites>

</phpunit>

Now, you can run the command and it will automatically detect the configuration file:

$ ./vendor/bin/phpunit

If you put the configuration file into another directory, you need to put the path to that directory in the command with the -c option.

Leave a Comment