Singleton and unit testing

前端 未结 12 1527
一生所求
一生所求 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:22

    it’s impossible to substitute a mock implementation for a singleton
    

    This is not true. You can subclass your singleton and setter inject a mock. Alternatively, you can use PowerMock to mock static methods. However the need to mock singletons can be symptomatic of poor design.

    The real problem is Singletons when abused turn into dependency magnets. Since they are accessible everywhere, it can appear more convenient to put the functions you need in them rather than delegating to an appropriate class, especially for programmers new to OOP.

    The testability problem is now you have a bunch of Singletons that are accessed by your object under test. Even though the object probably only uses a small fraction of methods in the Singletons, you still need to mock each Singleton and figure out which methods are depended on. Singletons with a static state (Monostate pattern) are even worse because you can have to figure out which interactions between objects are affected by the Singleton's state.

    Used carefully, Singletons and testability can occur together. For instance, in absence of a DI framework, you can use Singletons as your Factories and ServiceLocators, which you can setter inject to create a fake service layer for your end-to-end tests.

提交回复
热议问题