This forum is now a read-only archive. All commenting, posting, registration services have been turned off. Those needing community support and/or wanting to ask questions should refer to the Tag/Forum map, and to http://spring.io/questions for a curated list of stackoverflow tags that Pivotal engineers, and the community, monitor.

In my test, I want to unit test the code in someMethodIWantToTest, I do not want my test to also test out b.someMethod(). If I did not have Dependency Injection, then in someMethodIWantToTest might look like

So I wouldn't be able to swap out B with some stub or mock. The code in that method is too tightly coupled with B, so I only have a choice to do an integration test. Because trying to stub or mock out a dependency that is tightly coupled is more difficult.

2) Spring has your write POJO classes, and emphasis Java best practices of coding to interface, loose coupling and high cohesion. A great way to get that is to not use the keyword new in your code. Dependency Injection really helps in writing cleaner code. You will find your methods are smaller. Which in turn makes those methods a lot easier to test. From not having to write lots of tests for those methods. If I have a method with 100 lines of code in it, it will take a lot more positive/negative paths to test, making it more likely that I have maybe over 100 positive and negative paths to have to test to really test it. But if your method has 5-6 lines of code in it, then there might be 5 positive and negative paths. Dependency Injection really does write less code. Many times that code you write is using the new keyword to set things up.

3) Swapping out implementations is also easier because of Dependency Injection, which means I can swap out a lot of different mocks and stubs to get different variations on my tests without having to write a lot of test code and also maintain that code and also no longer need to write complex testing setup and teardown code.

4) For Integration tests, you can now easily put the pieces together using Spring and DI (Dependency Injection) So you can get really close to mimicking your real world production environment.