【问题标题】:ZF2 Unit Test Can't Find ServiceZF2 单元测试找不到服务
【发布时间】:2015-07-07 23:19:42
【问题描述】:

我正在对 ZF2 控制器进行单元测试,下面是测试类:

<?php
class RestControllerTest extends AbstractHttpControllerTestCase
{
    public function setUp()
    {
        Bootstrap::init();
        $this->setApplicationConfig(Bootstrap::getConfig());
        parent::setup();
    }

    public function testCreate()
    {
        $paramsArr = array(/** Params Here **/);
        $this->dispatch('/transcode', 'POST', $paramsArr);
        $this->assertResponseStatusCode(204);
        $this->assertControllerName('Transcode\Controller\Rest');
        $this->assertMatchedRouteName('transcode');
    }
}

我的单元测试失败,表明logger.transcode上出现ServiceNotFoundException,它附加到Transcode模块的事件管理器onBootstrap:

public function onBootstrap(MvcEvent $e)
    {
        $eventManager   = $e->getApplication()->getEventManager();
        $app            = $e->getTarget();
        $serviceManager = $app->getServiceManager();
        $eventManager->attach($serviceManager->get('Transcode\Listener'));
    }

Transcode\Listener 通过工厂实例化:

public function createService(ServiceLocatorInterface $serviceLocator)
{
    $logger = $serviceLocator->get('logger.transcode');
    $service = new TranscodeListener($logger);
    return $service;
}

最后,logger.transcode 是通过配置文件设置的,该文件将 logger.transcode 创建为 EnliteMonolog 模块中的抽象工厂。

知道为什么单元测试不能将侦听器附加到工作流吗?

根据 cmets 中的请求,Bootstrap 文件如下,尽管它是标准的 ZF2 Test Bootstrap 文件:

<?php

namespace TranscodeTest;

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

error_reporting(E_ALL | E_STRICT);
chdir(__DIR__);

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__ . '/TestConfiguration.php')) {
            $testConfig = include __DIR__ . '/TestConfiguration.php';
        }

        $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__,
                ),
            ),
        ));

        if (getenv('APPLICATION_ENV') != 'PRODUCTION') {
            Dotenv::load('../../../config');
        }
    }

    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();

【问题讨论】:

  • 我们能看到测试Bootstrap吗?
  • 多么令人难以置信的尴尬.....似乎我忘记将 EnliteMonolog 添加到 TestConfiguration 文件中。添加后,测试按预期运行。似乎有时候你盯着代码看的时间有点太长了.....

标签: php unit-testing zend-framework2


【解决方案1】:

令人尴尬的是,我似乎忘记将“EnliteMonolog”添加到 TestConfiguration.php 文件中。一旦我添加了该模块,测试就会按预期运行。貌似可以,其实看代码太久了

<?php
return array(
'modules' => array(
    'Transcode',
    /** Other modules needed **/
    'EnliteMonolog',
),
'module_listener_options' => array(
    'config_glob_paths'    => array(
        '../../../config/autoload/{,*.}{global,local}.php',
    ),
    'module_paths' => array(
        'module',
        'vendor',
    ),
),);

【讨论】:

    猜你喜欢
    • 2013-04-24
    • 2013-01-25
    • 2014-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-03
    相关资源
    最近更新 更多