Tag Archives: PHPUnit

Unit testing multiple ZF2 modules at once

Although it’s been over a year since the release of Zend Framework 2, I have yet to see compelling documentation on how to execute unit tests for an entire application.  If you are using Zend Studio 10, the default ZF2 module template provides testing architecture that is largely incompatible with multi-module testing.

Setup testing architecture

First, create a tests directory in your ZF2 application root.

cd /home/zf2-app
mkdir tests

PHPUnit configuration

After that, create the following PHPUnit XML configuration file in the newly-created tests directory. To add code coverage, simply add a logging entry to the XML file. Depending on how you run the tests, this allows code coverage for the entire application in one report, or a module-specific code coverage report.

<phpunit bootstrap="Bootstrap.php" backupGlobals="false">
        <testsuite name="application">
        <testsuite name="anothermodule">
            <directory suffix=".php">../module</directory>
                <directory suffix=".php">../module/*/tests</directory>


Next, you’ll need to create the Bootstrap.php file referenced in the PHPUnit configuration. In this case, the bootstrap will load and setup the application configuration file and load the specified modules. It is remarkably similar to the initialization process used when running the application in a normal context.


use ZendServiceManagerServiceManager;
use ZendMvcServiceServiceManagerConfig;


include_once 'init_autoloader.php';

$testsPath = __DIR__;
if (is_readable($testsPath . '/TestConfiguration.php')) {
    require_once $testsPath . '/TestConfiguration.php';
} else {
    require_once $testsPath . '/TestConfiguration.php.dist';

$configuration = include 'config/application.config.php';

$serviceManager = new ServiceManager(new ServiceManagerConfig($configuration));
$serviceManager->setService('ApplicationConfig', $configuration);
$moduleManager = $serviceManager->get('ModuleManager');

Next, create the TestConfiguration.php.dist file. This allows environment-specific configuration without affecting the code base.

touch TestConfiguration.php.dist

Run them jawns

Now that we’re finished with the setup, you’ll need to create a few tests. Once you have some tests to run, you can execute them using the commands below.

# Run all module tests

# Run tests for specific module
phpunit --testsuite anothermodule