开发者

Unit testing with Spring framework singleton beans

开发者 https://www.devze.com 2023-01-05 04:19 出处:网络
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 开发

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 开发者_JAVA百科those beans in your classes also considered bad for unit testing the same way singleton is?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消