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"> <testsuites> <testsuite name="application"> <directory>../module/Application</directory> </testsuite> <testsuite name="anothermodule"> <directory>../module/AnotherModule</directory> </testsuite> </testsuites> <filter> <whitelist> <directory suffix=".php">../module</directory> <exclude> <directory suffix=".php">../module/*/tests</directory> </exclude> </whitelist> </filter> </phpunit>
Bootstrapping
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.
<?php use ZendServiceManagerServiceManager; use ZendMvcServiceServiceManagerConfig; chdir(dirname(__DIR__)); 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'; unset($configuration['module_listener_options']['config_glob_paths']); unset($configuration['module_listener_options']['module_map_cache_enabled']); $serviceManager = new ServiceManager(new ServiceManagerConfig($configuration)); $serviceManager->setService('ApplicationConfig', $configuration); $moduleManager = $serviceManager->get('ModuleManager'); $moduleManager->loadModules();
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 phpunit # Run tests for specific module phpunit --testsuite anothermodule