Search code examples
phpzend-framework2phpunitservice-locator

ZF2: How to reset the ServiceManager during testing


My service manager is setup in my test bootstrap in what I suspect is a pretty standard manner, as follows:

    $serviceManager = new ServiceManager(new ServiceManagerConfig());
    $serviceManager->setService('ApplicationConfig', $config);
    $serviceManager->get('ModuleManager')->loadModules();
    static::$serviceManager = $serviceManager;

In the base class of my unit tests I am accessing and configuring the service manager as follows:

    $this->sm = Test\Bootstrap::getServiceManager();
    $this->sm->setAllowOverride(true);

In my individual tests I am then overriding the services with mocks, using $serviceManager->setService('MyService', $myMock).

This is fine except that I have to remember to unset each of the mocked services (which I am currently doing with $serviceManager->setService('MyService', null), otherwise the tests intefere with each other.

Is there any easier way to reset the service manager to it's bootstrapped state after each test is run? I can put a long list of services in the setUp() of the test base class and reset each there, but this could cause problems when a new service is added and the base class is not updated. I thought about cloning the service manager before each test, but this could be problematic (due to shallow cloning).

I could, of course, bootstrap the service manager in the setUp() of the base test case, but this seems like a lot of processing overhead.

Any ideas? Could peering be part of the solution?


Solution

  • I would say using setUp() for setting up a new test with a new instance of ServiceManager and other fresh configurations is exactly how it is supposed to be done.