Unit testing with singletons

前端 未结 4 1890
萌比男神i
萌比男神i 2020-11-27 09:27

I have prepared some automatic tests with the Visual Studio Team Edition testing framework. I want one of the tests to connect to the database following the normal way it is

4条回答
  •  清酒与你
    2020-11-27 10:14

    You are facing a more general problem here. If misused, Singletons hinder testabiliy.

    I have done a detailed analysis of this problem in the context of a decoupled design. I'll try to summarize my points:

    1. If your Singleton carries a significant global state, don’t use Singleton. This includes persistent storage such as Databases, Files etc.
    2. In cases, where dependency on a Singleton Object is not obvious by the classes name, the dependency should be injected. The need to inject Singleton Instances into classes proves a wrong usage of the pattern (see point 1).
    3. A Singleton’s life-cycle is assumed to be the same as the application’s. Most Singleton implementations are using a lazy-load mechanism to instantiate themselves. This is trivial and their life-cycle is unlikely to change, or else you shouldn’t use Singleton.

提交回复
热议问题