Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing a Zend Framework 2 Module With Factory

I'm trying to Unit Test a ZF2 Module I've written, specifically, a service object.

But I'm getting stuck on how to get the service manager (which calls my factory object) into the test class properly. My factory object injects my modules entity object, the Doctrine entity manager, and my module's entity repository.

How do I ensure that the the factory is properly called during the Unit Test?

like image 352
R Down Avatar asked Oct 03 '22 18:10

R Down


1 Answers

This is what I do in my 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;
}

And in your test class you can jus call Bootstrap::getServiceManager().

like image 83
Pradeep Avatar answered Oct 08 '22 19:10

Pradeep