2

I've got a question about a correct usage of Spring.

I know that some people use the DI "aggressively" so that they always use spring and completely eliminate the usage of word "new" in the production code.

On the other hand, I know that spring suits better for integration. For example like stated here this really looks reasonable and I tend to agree with this approach.

In my project the usage of spring is not really well-defined, so some people use it just for integration, others use it for everything that can be injected.

Now, I heard a lot of lecture about clean code and the art of unit testing, so I know that in order to write good unit testable code we should use DI container.

But since the unit test covers the code at the level of class (bean) It doesn't make sense to use more than 1 DI framework in the same project... So this effectively means that I should follow the extreme (first) approach.

So, my question is, what are the general rules of thumb given the fact that after all, I want to organize my code so that it will be easy unit-testable?

  • Swallow the pill and finish drinking the koolaid. Dive completely into the framework and see how the framework facilitates its testing. – user40980 Feb 29 '16 at 3:33
  • I completely agree that Spring can shine when it comes to Integration Testing. But its not the question. In unit testing I don't use spring at all (I can't really load spring each time I have a unit test - it just too slow). So, I know that spring provides reasonable mocks for stuff like Environment, and its cool if I need it, but I consider more "general case". In general -should spring bean have its dependencies and manage them or all those should also be spring beans (recursively for the whole project, unless its a creational pattern list factory or builder) – Mark Bramnik Feb 29 '16 at 7:35
1

I think DI is used essentially for reducing dependency with an added benefit of easy unit testing. My personal opinion is, if it is used only for unit testing, I'd instead use a tool like mockito and power mock.

So the answer would be , if you really want to organize your unit tests and make it easy, use tools like mockito and power mock. Stop depending on DI , to make your code unit-testable.

  • Interesting, I'm totally aware of Mockito/Power Mock and so on, and I do use them in unit tests And I don't use Spring for those of course. But I thought that DI (especially constructor injection) is very convenient when it comes to definition of class dependencies. In unit tests these get injected with mocks created by mockito. Otherwise, if you don't use "DI code style", how would you unit test them? Injection by reflection - too fragile, no??? – Mark Bramnik Feb 29 '16 at 7:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.