我对自己的 SessionManager 服务进行单元测试时遇到问题。我在单元测试中没有错误,但会话没有在数据库中创建,我无法写入存储。这是我的代码:
会话管理器工厂:
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()
Module.php
命名空间中的方法Admin
:
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());
}
如何测试此服务以及为什么未创建会话?