我使用本教程http://samsonasik.wordpress.com/2012/10/23/zend-framework-2-create-login-authentication-using-authenticationservice-with-rememberme/开发了简单的身份验证。一切正常,但现在我有单元测试问题。
要检查用户是否已验证我正在使用:
public function onBootstrap(MvcEvent $e)
{
$auth = $e->getApplication()->getServiceManager()->get('AuthService');
$e->getTarget()->getEventManager()->getSharedManager()
->attach('Admin', \Zend\Mvc\MvcEvent::EVENT_DISPATCH,
function($e) use ($auth) {
$currentRouteName = $e->getRouteMatch()->getMatchedRouteName();
$allowed = array(
'admin/login',
'admin/',
);
if (in_array($currentRouteName, $allowed)) {
return;
}
if (!$auth->hasIdentity()) {
$url = $e->getRouter()->assemble(array(),
array('name' => 'admin/login'));
$response = $e->getResponse();
$response->getHeaders()->addHeaderLine('Location', $url);
$response->setStatusCode(302);
$response->sendHeaders();
}
});
}
我的模拟代码:
$authMock = $this->getMock('Zend\Authentication\AuthenticationService');
$authMock->expects($this->once())
->method('hasIdentity')
->will($this->returnValue(true));
$serviceManager = $this->getApplicationServiceLocator();
$serviceManager->setAllowOverride(true);
$serviceManager->setService('AuthService', $authMock);
我的问题是在单元测试期间没有调用模拟hasIdentity
。我做错了什么。
答案 0 :(得分:1)
问题出在bootstrap中。在模仿之前调用onBootstrap。因此需要在事件处理程序中调用get('AuthService')
。这是工作bootstrap示例:
public function onBootstrap(MvcEvent $e)
{
$sm = $e->getApplication()->getServiceManager();
$e->getTarget()->getEventManager()->getSharedManager()
->attach('Admin', \Zend\Mvc\MvcEvent::EVENT_DISPATCH,
function($e) use ($sm) {
$auth = $sm->get('AuthService');
$currentRouteName = $e->getRouteMatch()->getMatchedRouteName();
$allowed = array(
'admin/login',
'admin/',
);
if (in_array($currentRouteName, $allowed)) {
return;
}
if (!$auth->hasIdentity()) {
$url = $e->getRouter()->assemble(array(),
array('name' => 'admin/login'));
$response = $e->getResponse();
$response->getHeaders()->addHeaderLine('Location', $url);
$response->setStatusCode(302);
$response->sendHeaders();
}
});
}