Everyone knows that code that uses Service Locator is hard to test while Dependency Injection should be used instead.
But I don't get why the code that uses 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 perfecly testable? Why Service Locator is bad in this case?
Aucun commentaire:
Enregistrer un commentaire