Why is it hard to unit test a system that depends on singletons?

前端 未结 7 1838
Happy的楠姐
Happy的楠姐 2020-12-02 23:41

I\'ve read cases for and against using the singleton pattern. One common case against describes the difficulties in unit testing with singletons, but I\'m unclear as to why

7条回答
  •  温柔的废话
    2020-12-02 23:54

    Singletons are a problem for several reasons:

    • They're a special case of a Service Locator, which provides a mechanism to "get me one of those" that isn't necessarily easy to override when needed.
    • They provide an entry point to read or write global variables. Wrapping those global variables up in an object with only one instance that is globally accessible via the Singleton pattern doesn't magically make them stop being global variables.
    • They're trouble for maintenance too. For example, what happens when they stop being a true Singleton -- maybe you have to access two databases instead of "the database"?

提交回复
热议问题