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条)

报告相同问题?

悬赏问题

  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证