Singleton and unit testing

前端 未结 12 1538
一生所求
一生所求 2021-01-30 10:24

The Effective Java has the following statement on unit testing singletons

Making a class a singleton can make it difficult to test its clients, as it’s im

12条回答
  •  无人共我
    2021-01-30 11:08

    I think it actually depends on the implementation of the singleton access pattern.

    For example

    MySingleton.getInstance()
    

    Might be very dificult to test while

    MySingletonFactory mySingletonFactory = ...
    mySingletonFactory.getInstance() //this returns a MySingleton instance or even a subclass
    

    Doesn't provide any information about the fact that its using a singleton. So you can freely replace your factory.

    NOTE: a singleton is defined by being only one instance of that class in an application, however the way it's obtained or stored doesn't have to be through static means.

提交回复
热议问题