1

I've read a lot of topic about "Singleton is hard for testing". Most of them posted in 2010 and 2011.

And it tried to figured out why Singleton is bad for testing by using PowerMock. But everything worked fine and i still couldn't find what is the devil of Singleton.

Can you give any example of Singleton in testing and point out the problem?

Tran Thien Chien
  • 643
  • 2
  • 6
  • 17
  • 3
    Possible duplicate of [Why is it hard to unit test a system that depends on singletons?](http://stackoverflow.com/questions/3876951/why-is-it-hard-to-unit-test-a-system-that-depends-on-singletons) – andih Jul 12 '16 at 08:42
  • 1
    `PowerMock` is different because it's able to stub static methods. Many other frameworks can't do that and then you have problems and have to make some extra effort like Dependency Injection to make singletons testable. – Mousa Jul 13 '16 at 05:20

2 Answers2

1

From a .Net perspective, I suppose it's because many mocking frameworks don't easily support the ability provide mocks, given how the Singleton pattern is commonly implemented, i.e. with static fields, no constructor and a read-only property. Using this typical pattern provides little for external code to hook into.

However, you can use the 'Ambient Context' pattern to achieve the same effect and support 'testability'.

David Osborne
  • 6,436
  • 1
  • 21
  • 35
1

Another interesting issue, depending on your testing framework, is that the singleton might maintain state across tests.

This makes it hard to guarantee that the symptoms seen in one set of unit tests are due to that set of tests, and not the previously run tests. Or if you have a testing framework that randomly re-orders tests, you might find that the behaviour of the tests changes between runs.

Arunas
  • 1,282
  • 1
  • 11
  • 17