unit testing and Static methods

前端 未结 3 475
清歌不尽
清歌不尽 2020-11-28 21:45

Reading up and picking up on unit testing, trying to make sense of the following post on that explains the hardships of static function calls.

I don\'t clearly unde

3条回答
  •  遥遥无期
    2020-11-28 22:24

    Sebastian Bergmann agrees with Misko Hevery and quotes him frequently:

    • Stubbing and Mocking Static Methods

    Unit-Testing needs seams, seams is where we prevent the execution of normal code path and is how we achieve isolation of the class under test. Seams work through polymorphism, we override/implement class/interface and then wire the class under test differently in order to take control of the execution flow. With static methods there is nothing to override. Yes, static methods are easy to call, but if the static method calls another static method there is no way to override the called method dependency.

    The main issue with static methods is that they introduce coupling, usually by hardcoding the dependency into your consuming code, making it difficult to replace them with stubs or mocks in your Unit-Tests. This violates the Open/Closed Principle and the Dependency Inversion Principle, two of the SOLID principles.

    You are absolutely right that statics are considered harmful. Avoid them.

    Check the links for additional information please.

    Update: note that while statics are still considered harmful, the capability to stub and mock static methods has been removed as of PHPUnit 4.0

提交回复
热议问题