2013-10-05 58 views
4

我想单元测试一个ZF2模块我写了,特别是,一个服务对象。单元测试一个Zend框架2模块与工厂

但我遇到了如何让服务管理器(它调用我的工厂对象)正确地进入测试类。我的工厂对象注入我的模块实体对象,Doctrine实体管理器和我的模块的实体存储库。

如何确保在单元测试期间正确调用工厂?

+1

您是否阅读过[http://framework.zend.com/manual/2.2/en/tutorials/unittesting.html](http://framework.zend.com/manual/2.2/en/tutorials)上的教程/unittesting.html)?还有一个关于_配置测试服务管理器的部分_。 – Matthias

回答

3

这是我做的,我bootstrap.php中:

public static function init() 
{ 
    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 : ''); 

    $serviceManager = new ServiceManager(new ServiceManagerConfig()); 
    $serviceManager->setService(
     'ApplicationConfig', 
     $testConfig 
    ); 
    $serviceManager->get('ModuleManager')->loadModules(); 
    $serviceManager->setAllowOverride(true); 
    static::$serviceManager = $serviceManager; 
} 

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

并在测试类,你可以强制调用引导:: getServiceManager()。