Zend框架2 -如何单元测试自己的会话服务


Zend Framework 2 - how to unit test own session service?

我有一个问题与我自己的SessionManager服务的单元测试。我在单元测试中没有错误,但会话不是在数据库中创建的,我无法写入存储。下面是我的代码:

SessionManagerFactory:

namespace Admin'Service;
use Zend'ServiceManager'FactoryInterface;
use Zend'ServiceManager'ServiceLocatorInterface;
use Zend'ServiceManager'ServiceManager;
use Zend'Session'SaveHandler'DbTableGatewayOptions as SessionDbSavehandlerOptions;
use Zend'Session'SaveHandler'DbTableGateway;
use Zend'Session'Config'SessionConfig;
use Zend'Session'SessionManager;
use Zend'Db'TableGateway'TableGateway;
class SessionManagerFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        return $this;
    }
    public function setUp(ServiceManager $serviceManager)
    {
        $sessionOptions = new SessionDbSavehandlerOptions();
        $sessionOptions->setDataColumn('data')
                       ->setIdColumn('id')
                       ->setModifiedColumn('modified')
                       ->setLifetimeColumn('lifetime')
                       ->setNameColumn('name');
        $dbAdapter = $serviceManager->get('Zend'Db'Adapter'Adapter');
        $sessionTableGateway = new TableGateway('zf2_sessions', $dbAdapter);
        $sessionGateway = new DbTableGateway($sessionTableGateway, $sessionOptions);
        $config = $serviceManager->get('Configuration');
        $sessionConfig = new SessionConfig();
        $sessionConfig->setOptions($config['session']);
        $sessionManager = new SessionManager($sessionConfig);
        $sessionManager->setSaveHandler($sessionGateway);
        return $sessionManager;
    }
}

GetServiceConfig() from Module.php in Admin namespace:

public function getServiceConfig()
    {
        return array(
            'factories' => array(
                'Zend'Authentication'Storage'Session' => function($sm) {
                    return new StorageSession();
                },
                'AuthService' => function($sm) {
                    $dbAdapter = $sm->get('Zend'Db'Adapter'Adapter');
                    $authAdapter = new AuthAdapter($dbAdapter, 'zf2_users', 'email', 'password');
                    $authService = new AuthenticationService();
                    $authService->setAdapter($authAdapter);
                    $authService->setStorage($sm->get('Zend'Authentication'Storage'Session'));
                    return $authService;
                },
                'SessionManager' => function($serviceManager){
                    $sessionManager = new SessionManagerFactory();
                    return $sessionManager->setUp($serviceManager);
                }
            )
        );
    }

setUp()方法从单元测试文件:

protected function setUp()
    {
        $bootstrap             = 'Zend'Mvc'Application::init(include 'config/app.config.php');
        $this->controller      = new SignController;
        $this->request         = new Request;
        $this->routeMatch      = new RouteMatch(array('controller' => 'sign'));
        $this->event           = $bootstrap->getMvcEvent();
        // Below line should start session and storage it in Database. 
        $bootstrap->getServiceManager()->get('SessionManager')->start();
        // And this line should add test variable to default namespace of session, but doesn't - blow line is only for quick test. I will write method for test write to storage.
        Container::getDefaultManager()->test = 12;
        $this->event->setRouteMatch($this->routeMatch);
        $this->controller->setEvent($this->event);
        $this->controller->setEventManager($bootstrap->getEventManager());
        $this->controller->setServiceLocator($bootstrap->getServiceManager());
    }

如何测试这个服务,为什么没有创建会话?

我想你误解了工厂模式。您的工厂应该如下所示。据我所知,单独的setUp方法在任何地方都不会被调用。你不用在任何地方手动调用它。

class SessionManagerFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $sessionOptions = new SessionDbSavehandlerOptions();
        $sessionOptions->setDataColumn('data')
                       ->setIdColumn('id')
                       ->setModifiedColumn('modified')
                       ->setLifetimeColumn('lifetime')
                       ->setNameColumn('name');
        $dbAdapter = $serviceManager->get('Zend'Db'Adapter'Adapter');
        $sessionTableGateway = new TableGateway('zf2_sessions', $dbAdapter);
        $sessionGateway = new DbTableGateway($sessionTableGateway, $sessionOptions);
        $config = $serviceManager->get('Configuration');
        $sessionConfig = new SessionConfig();
        $sessionConfig->setOptions($config['session']);
        $sessionManager = new SessionManager($sessionConfig);
        $sessionManager->setSaveHandler($sessionGateway);
        return $sessionManager;
    }
}

下面所有的代码对我都有效。我认为你错过了一些其他的东西,但上面应该解决它。请查看下面的SEE ME评论。此外,添加一个onBootstrap方法到你的Module.php像我下面有,并确保调用$sessionManager = $serviceManager->get( 'SessionManager' );在你的情况下,这样你的SessionFactory实际上被调用。你已经在单元测试的setup()函数中调用了它,但是如果你在模块中调用它,你就不必自己手动调用它了。

应用程序。config我有这个

'session' => array(
        'name'                => 'PHPCUSTOM_SESSID',
        'cookie_lifetime'     => 300, //1209600, //the time cookies will live on user browser
        'remember_me_seconds' => 300, //1209600 //the time session will live on server
        'gc_maxlifetime'      => 300
    )
'db' => array(
        'driver' => 'Pdo_Sqlite',
        'database' => '/tmp/testapplication.db'
    ),

我的会话工厂是非常相似的,但我有一个额外的代码行。查看评论

use Zend'ServiceManager'FactoryInterface,
    Zend'ServiceManager'ServiceLocatorInterface,
    Zend'Session'SessionManager,
    Zend'Session'Config'SessionConfig,
    Zend'Session'SaveHandler'DbTableGateway as SaveHandler,
    Zend'Session'SaveHandler'DbTableGatewayOptions as SaveHandlerOptions,
    Zend'Db'Adapter'Adapter,
    Zend'Db'TableGateway'TableGateway;
class SessionFactory
    implements FactoryInterface
{
    public function createService( ServiceLocatorInterface $sm )
    {
        $config = $sm->has( 'Config' ) ? $sm->get( 'Config' ) : array( );
        $config = isset( $config[ 'session' ] ) ? $config[ 'session' ] : array( );
        $sessionConfig = new SessionConfig();
        $sessionConfig->setOptions( $config );
        $dbAdapter = $sm->get( ''Zend'Db'Adapter'Adapter' );
        $sessionTableGateway = new TableGateway( 'sessions', $dbAdapter );
        $saveHandler = new SaveHandler( $sessionTableGateway, new SaveHandlerOptions() );
        $manager = new SessionManager();
        /******************************************/
        /* SEE ME : I DON'T SEE THE LINE BELOW IN YOUR FACTORY. It probably doesn't matter though. 
        /******************************************/
        $manager->setConfig( $sessionConfig );  
        $manager->setSaveHandler( $saveHandler );
        return $manager;
    }

在我的一个模块中,我有以下

public function onBootstrap( EventInterface $e )
    {
        // You may not need to do this if you're doing it elsewhere in your
        // application
        /* @var $eventManager 'Zend'EventManager'EventManager  */
        /* @var $e 'Zend'Mvc'MvcEvent */
        $eventManager = $e->getApplication()->getEventManager();
        $serviceManager = $e->getApplication()->getServiceManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach( $eventManager );
        try
        {
            //try to connect to the database and start the session
            /* @var $sessionManager SessionManager */
            $sessionManager = $serviceManager->get( 'Session' );
            /******************************************/
            /* SEE ME : Make sure to start the session
            /******************************************/
            $sessionManager->start();
        }
        catch( 'Exception $exception )
        {
            //if we couldn't connect to the session then we trigger the
            //error event
            $e->setError( Application::ERROR_EXCEPTION )
                ->setParam( 'exception', $exception );
            $eventManager->trigger( MvcEvent::EVENT_DISPATCH_ERROR, $e );
        }
    }
}

这是我的getServiceConfigMethod

public function getServiceConfig()
{
    return array(
        'factories' => array(
            'Session' => ''My'Mvc'Service'SessionFactory',
            ''Zend'Db'Adapter'Adapter' => ''Zend'Db'Adapter'AdapterServiceFactory'
        )
    );
}

我现在正在使用sqlite,所以这个表必须已经存在于你的sqlite文件中。

如果你使用的是mysql,它也应该存在于数据库中,你应该在application.config.php文件中修改你的db设置。