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

前端 未结 7 1882
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:50

    I don't recall ever reading that, but I suspect the problem is the fact that you can only create one. In some cases, that may not be a problem, just test it normally.

    But what if you want to create and test a different one, perhaps with different constructor/factory method parameters? Do you restart the JVM? Or create your singleton so that it's not really a singleton and can be reset? Not good.

提交回复
热议问题