In Module.php, i implemented the code to check for authentication of a user before allowing access to restricted pages.
Here is my Module.php
<?php namespace Application; use Zend\Mvc\ModuleRouteListener; use Zend\Mvc\MvcEvent; use Zend\Mvc\Router\RouteMatch; class Module { protected $whitelist = array('authenticate', 'home'); public function onBootstrap(MvcEvent $event) { $application = $event->getApplication(); $eventManager = $application->getEventManager(); $serviceManager = $application->getServiceManager(); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); $authService = $serviceManager->get('Zend\Authentication\AuthenticationService'); $whitelist = $this->whitelist; $eventManager->attach(MvcEvent::EVENT_ROUTE, function ($e) use ($whitelist, $authService) { $routeMatch = $e->getRouteMatch(); //No route match, this is a 404 if (!$routeMatch instanceof RouteMatch) { return; } //Route is whitelisted $matchedRouteName = $routeMatch->getMatchedRouteName(); if (in_array($matchedRouteName, $whitelist)) { return; } //User is authenticated if ($authService->hasIdentity()) { return; } //Redirect users $router = $e->getRouter(); $url = $router->assemble(array(), array( 'name' => 'authenticate' )); $response = $e->getResponse(); $response->getHeaders()->addHeaderLine('Location', $url); $response->setStatusCode(302); return $response; }, -100); } public function getConfig() { return include __DIR__ . '/config/module.config.php'; } public function getAutoloaderConfig() { return array( 'Zend\Loader\StandardAutoloader' => array( 'namespaces' => array( __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__, ), ), ); } public function getServiceConfig() { return array( 'factories' => array( 'Zend\Authentication\AuthenticationService' => function ($serviceManager) { return $serviceManager->get('doctrine.authenticationservice.orm_default'); } ) ); } } This works perfectly in browser, but when running the unit test it throws the following error.
Zend\ServiceManager\Exception\ServiceNotFoundException: Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for doctrine.authenticationservice.orm_default The problem is the service manager in onBoostrap is not able to initialize authentication adapter, this is the code with problem
$authService = $serviceManager->get('Zend\Authentication\AuthenticationService'); When i disable $authService all unit test runs successfully, i am not able to figure out the exact issue causing this, what could be the possible issue here?
Thanks.