dou31797719 2015-03-23 21:39
浏览 50

如果仍然可以模拟对象,为什么Service Locator不适合测试?

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

    return true;

If we want to test this code we can simply mock our object "Dependency", example:

 function testMyFunction() {
        $mock = \Mockery::mock('Dependency');

        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.

  • 写回答



      相关推荐 更多相似问题


      • ¥40 python,计算机程序运行结果很奇怪
      • ¥15 有关时间计算器的问题
      • ¥200 Chrome浏览器自动保存密码需要解密!来人
      • ¥18 关于#c语言#的问题:如何把下面几个代码放在一起编序号,然后输入对应数字运行对应代码,还可以返回重输
      • ¥30 windows下无法运行go test的问题
      • ¥15 多个Rigify骨骼 导入一起 后 没有 控制器面板
      • ¥15 想问一下sprak ada语言的pre和post怎么设
      • ¥15 使用python将分子模拟输出.gro文件
      • ¥15 港诡实录的背包系统拆解
      • ¥15 宽带IP网络路由器的初始路由表和最终路由表