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
    $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.

  • 写回答

2条回答 默认 最新

  • doudu7626 2015-03-24 06:47
    关注

    Everyone knows that code that uses Service Locator is hard to test while Dependency Injection should be used instead.

    I didn't know that...

    The reason that Service Locator is an anti-pattern isn't because it makes the code hard to test (it doesn't), but because it makes it hard to maintain.

    Service Locator breaks encapsulation because you can use it from anywhere within your code, and a client has no chance of detecting this without reading through all the code that might potentially use it.

    Dependency Injection is a better option, because it solves the same problems with fewer disadvantages.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。