Unit testing with Spring singleton beans framework

His general view is that Singleton is bad for unit testing.

But what about having an IoC container, such as the Spring framework for managing your beans, which is single by default? Does using these beans in your classes also be considered bad for unit testing in the same way as singleton?

+3
source share
2 answers

The point about how singletones are handled in Spring is that there is no code in the singleton that restricts what it's called, it's just a POJO. Spring is responsible for ensuring that everyone receives the same instance. This means that if you want to write unit test, your test should not use Spring for it at all, the test can create a singleton instance, like any other POJO, as part of the test setup process, and the test code can connect mocks to its dependencies.

This is singleton code, providing it with a singleton, which makes testing difficult, and Spring is no longer a problem.

+2
source

Singleton is not bad. They are very helpful.

Singleton Design Pattern, , , .

IoC, Spring, , .

Spring , .

+5

Source: https://habr.com/ru/post/1752605/


All Articles