Everyone knows that code that uses Service Locator is hard to test while Dependency Injection should be used instead.
But why Service Locator is hard to test if we can still easily mock each objects?
Consider this example (written in PHP but it could be any language)
// method we want to test that has a dependency
public myFunction() {
$someDependency = Registry::getService('Dependency');
// do something with the dependendcy
$someDependency->doSomething();
return true;
}
If we want to test this code we can simply mock our object "Dependency", example:
function testMyFunction() {
$mock = \Mockery::mock('Dependency');
$mock->shouldReceive('doSomething')->once();
Registry::set('Dependency', $mock); // set the double
$workerObject = new MyClass;
$this->assertTrue( $workerObject->myFunction() );
}
Isn't this code testable? Why Service Locator is bad in this case?
Note that we all know how bad a Service locator because it hides dependency and violets SOLID principles. But in this case i am simply referring to the testing aspect.