The problem was in bootstrap. onBootstrap is being called before mocking. So get('AuthService')
needs to be called in event handler. Here is working bootstrap example:
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();
}
});
}