Question

Being tired of playing with PHPUnit and ZF2 testing, I decided to post my problem.

Here's the problem, I'm trying to make my first unit test in my Application module. Everything works except the ServiceManager... I always get errors about ViewResolver, ViewTemplateMapResolver, etc...

Here's the first exception thrown which cause everything else...

Caused by Zend\View\Exception\InvalidArgumentException: Zend\View\Resolver\TemplateMapResolver::setMap: expects an array or Traversable, received "boolean"

Here's my Bootstrap:

<?php
namespace ApplicationTest;//Change this namespace for your test

use Zend\Loader\AutoloaderFactory;
use Zend\Mvc\Service\ServiceManagerConfig;
use Zend\ServiceManager\ServiceManager;
use Zend\Stdlib\ArrayUtils;
use RuntimeException;

error_reporting(E_ALL | E_STRICT);
chdir(__DIR__);
define('ENV', 'dev');

class Bootstrap
{
    protected static $serviceManager;
    protected static $config;
    protected static $bootstrap;

    public static function init()
    {
        // Load the user-defined test configuration file, if it exists; otherwise, load
        if (is_readable(__DIR__ . '/TestConfig.php')) {
            $testConfig = include __DIR__ . '/TestConfig.php';
        } else {
            $testConfig = include __DIR__ . '/TestConfig.php.dist';
        }

        $zf2ModulePaths = array();

        if (isset($testConfig['module_listener_options']['module_paths'])) {
            $modulePaths = $testConfig['module_listener_options']['module_paths'];
            foreach ($modulePaths as $modulePath) {
                if (($path = static::findParentPath($modulePath)) ) {
                    $zf2ModulePaths[] = $path;
                }
            }
        }

        $zf2ModulePaths  = implode(PATH_SEPARATOR, $zf2ModulePaths) . PATH_SEPARATOR;
        $zf2ModulePaths .= getenv('ZF2_MODULES_TEST_PATHS') ?: (defined('ZF2_MODULES_TEST_PATHS') ? ZF2_MODULES_TEST_PATHS : '');

        static::initAutoloader();

        // use ModuleManager to load this module and it's dependencies
        $baseConfig = array(
            'module_listener_options' => array(
                'module_paths' => explode(PATH_SEPARATOR, $zf2ModulePaths),
            ),
        );

        $config = ArrayUtils::merge($baseConfig, $testConfig);

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

        static::$serviceManager = $serviceManager;
        static::$config = $config;
    }

    public static function getServiceManager()
    {
        return static::$serviceManager;
    }

    public static function getConfig()
    {
        return static::$config;
    }

    protected static function initAutoloader()
    {
        $vendorPath = static::findParentPath('vendor');

        if (is_readable($vendorPath . '/autoload.php')) {
            $loader = include $vendorPath . '/autoload.php';
        } else {
            $zf2Path = getenv('ZF2_PATH') ?: (defined('ZF2_PATH') ? ZF2_PATH : (is_dir($vendorPath . '/ZF2/library') ? $vendorPath . '/ZF2/library' : false));

            if (!$zf2Path) {
                throw new RuntimeException('Unable to load ZF2. Run `php composer.phar install` or define a ZF2_PATH environment variable.');
            }

            include $zf2Path . '/Zend/Loader/AutoloaderFactory.php';

        }

        AutoloaderFactory::factory(array(
            'Zend\Loader\StandardAutoloader' => array(
                'autoregister_zf' => true,
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/' . __NAMESPACE__,
                ),
            ),
        ));
    }

    protected static function findParentPath($path)
    {
        $dir = __DIR__;
        $previousDir = '.';
        while (!is_dir($dir . '/' . $path)) {
            $dir = dirname($dir);
            if ($previousDir === $dir) return false;
            $previousDir = $dir;
        }
        return $dir . '/' . $path;
    }
}

Bootstrap::init();

And here's my TestConfig.php.dist:

<?php
return array(
    'modules' => array(
        'Application',
        'Account',
        'Blog',
    ),
    'module_listener_options' => array(
        'config_glob_paths'    => array(
            'config/autoload/{,*.}{global,local}.php',
        ),
        'module_paths' => array(
            'module',
            'vendor',
        ),
    ),
);

Now that my Bootstrap is done. If I run PHPUnit, I get this:

PHPUnit 3.7.34 by Sebastian Bergmann.

Configuration read from {ZF_APP}\module\Application\tests\phpunit.xml

Time: 192 ms, Memory: 3.00Mb

No tests executed!

Now, as soon as I create a TestCase like this one:

<?php

namespace ApplicationTest\Controller;

use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;
use Zend\Http\Request;
use Zend\Http\Response;
use Zend\Mvc\MvcEvent;
use Zend\Mvc\Router\RouteMatch;
use Application\Controller\IndexController;
use ApplicationTest\Bootstrap;

class IndexControllerTest extends AbstractHttpControllerTestCase
{

    public function setUp()
    {
        $this->setApplicationConfig(
            Bootstrap::getConfig()
        );

        parent::setUp();
    }

    public function testCanAccessIndexAction()
    {
        $this->dispatch('/');

        $this->assertResponseStatusCode(200);
        $this->assertModuleName('Application');
        $this->assertControllerName('Application\Controller\Index');
        $this->assertControllerClass('IndexController');
        $this->assertActionName('index');
        $this->assertMatchedRouteName('home');
    }

    public function testCanAccessSitemapAction()
    {
        $this->dispatch('/sitemap.xml');

        $this->assertResponseStatusCode(200);
        $this->assertModuleName('Application');
        $this->assertControllerName('Application\Controller\Index');
        $this->assertControllerClass('IndexController');
        $this->assertActionName('sitemap');
        $this->assertMatchedRouteName('sitemap');
    }

}

I get a lot of errors about ServiceManager and ViewManager...

Can anyone help me please? I tried to search Github, docs, ZF2 Skeleton, etc... Nothing work.

Was it helpful?

Solution 2

i had some trouble too when i wanted to unit tests my application, few weeks ago. You have a service manager trouble. If this help this is my bootstrap.php in myApp/tests Be careful, because i centralize my tests launcher, but i'm doing my tests inside each modules.

namespace TestsAll;
use Zend\ServiceManager\ServiceManager,
    Zend\Mvc\Service\ServiceManagerConfig;   
class Bootstrap
{
    static public $config;
    static public $sm;
    static public $em;

    static public function go()
    {
        chdir(dirname(__DIR__));
        include __DIR__ . '/../init_autoloader.php';
        self::$config = include 'config/application.config.php';
        \Zend\Mvc\Application::init(self::$config);
        self::$sm = self::getServiceManager(self::$config);
        self::$em = self::getEntityManager(self::$sm);
    }

    static public function getServiceManager($config)
    {
        $serviceManager = new ServiceManager(new ServiceManagerConfig);
        $serviceManager->setService('ApplicationConfig', $config);
        $serviceManager->get('ModuleManager')->loadModules();
        return $serviceManager;
    }

    static public function getEntityManager($serviceManager)
    {
        return $serviceManager->get('doctrine.entitymanager.orm_default');
        }
    } 
    Bootstrap::go();

i hope this help

OTHER TIPS

You should just be able to do something like this:

class MyHttpTestCase extends AbstractHttpControllerTestCase {

protected function setUp() {
    $config = include __DIR__ . '/../path/to/config/application.config.php';
    $this->setApplicationConfig($config);
    parent::setUp();
}

public function testYourStuffHere(){...}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top