views:

46

answers:

2

It’s a general consensus that Singleton is bad for unit-testing.

But what about having an IoC container like the Spring framework to control your beans which are singletons by default? Is using those beans in your classes also considered bad for unit testing the same way singleton is?

+3  A: 

Singletons are not a bad thing. They are very much a good thing.

The Singleton Design Pattern, however, is generally considered bad, since it can hamper testing.

When you have an IoC framework like Spring to manage your singletons for you, you're fine.

Spring proves a unit testing framework which manages singletons during the test lifecycle.

skaffman
So is the reason why it is not harmful to use Spring's singleton beans because of Spring's ability inject dependency?
Glide
@Glide the reason is that the lifecycle of the bean is controlled by an outside container and is not enforced by the bean class nor do the users of the bean have any idea if it is a singleton or not. There are really two definitions of singleton at play here: 1) the design pattern in which classes control their own lifecycle and 2) Spring's definition which refers to the lifecycle *only*.
matt b
A: 

The point of how singletons are handled in Spring is that there is no code in the singleton limiting how it is called, it's just a POJO. Spring is in charge of making sure everyone gets the same instance of it. That means if you want to write a unit test for it your test doesn't have to use Spring at all, the test can instantiate the singleton like any other POJO as part of the test setup process, and the test code can plug in mocks for its dependencies.

It's the code in the singleton enforcing its singleton-ness that makes it hard to test, with Spring that's no longer an issue.

Nathan Hughes