ZF2 - Mocking service requested in Module.php
I am trying to test a controller of my ZF2 application. Suppose this controller is in my module.A
In the method of the of the module I am using the service manager to retrieve a service of another module, say , that I am not loading.onBootstrap
Module.php
A
B
How can set a mock of the requested service in the service manager? Mind that I can not use to do this in my test, since this is already calling the method of my module.$this->getApplicationServiceLocator()
Module.onBootstrap
A
To post some code, this is what I am doing at the moment
bootstrap.php
namespace Application;
use Zend\Mvc\Service\ServiceManagerConfig;
use Zend\ServiceManager\ServiceManager;
use RuntimeException;
class Bootstrap
{
protected static $serviceManager;
public static function init()
{
$modulePath = static::findParentPath('module');
$vendorPath = static::findParentPath('vendor');
if (is_readable($vendorPath . '/autoload.php')) {
$loader = include $vendorPath . '/autoload.php';
} else {
throw new RuntimeException('Cannot locate autoload.php');
}
$config = [
'modules' => [
'Application',
],
'module_listener_options' => [
'module_paths' => [
$modulePath,
$vendorPath
]
]
];
$serviceManager = new ServiceManager(new ServiceManagerConfig());
$serviceManager->setService('ApplicationConfig', $config);
$serviceManager->get('ModuleManager')->loadModules();
static::$serviceManager = $serviceManager;
}
protected static function findParentPath($path)
{
$dir = __DIR__;
$previousDir = '.';
while (!is_dir($dir . '/' . $path)) {
$dir = dirname($dir);
if ($previousDir === $dir) {
return false;
}
$previousDir = $dir;
}
return $dir . '/' . $path;
}
public static function getServiceManager()
{
return static::$serviceManager;
}
}
Bootstrap::init();
my actual test class
namespace Application\Functional;
use Application\Bootstrap;
use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;
class ValidateCustomerRegistrationTest extends AbstractHttpControllerTestCase
{
public function setUp()
{
$serviceManager = Bootstrap::getServiceManager();
$applicationConfig = $serviceManager->get('ApplicationConfig');
$this->setApplicationConfig($applicationConfig);
parent::setUp();
}
public function testRegisterValidUserWithOnlyEquomobiliData()
{
$this->getApplicationServiceLocator();
}
}
Module.php simplified
namespace Application
Class Module
{
public function onBootstrap(MvcEvent $e)
{
$serviceManager = $e->getApplication()->getServiceManager();
$service = $serviceManager->get('Service\From\Other\Module');
}
}