Java – unit testing using spring framework singleton beans

It is generally believed that singleton is not conducive to unit testing

However, can an IOC container like the spring framework control your bean to be a singleton by default? Using those beans in your class is also considered bad for unit testing, just like being single?

Solution

The key to how to handle singletons in spring is that there is no code to limit its calling method. It is just a POJO Spring is responsible for ensuring that everyone gets the same instance This means that if you want to write unit tests for it, your tests do not need to use spring at all. Tests can instantiate singletons like any other POJO in the test setup process, and test code can be inserted to simulate its dependencies

This is the code for a singleton to execute its singleton, which makes it difficult to test, and spring is no longer a problem

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>