I am new to unit testing and i need to use dependency injection pattern.
Asked
Active
Viewed 435 times
-4
-
1What other patterns? Why do you *need* to use it? I do not get the question. – Peter Bons Feb 21 '17 at 08:45
-
Using dependency injection in your _code_ can help you to write _testable_ code. You don't need to use it, and whether dependency injection is best for your code (not unit tests) depends on the application – Nibor Feb 21 '17 at 08:50
-
If You have complex system, than DI can shine. You can decompose the system into smaller components, which can be tested separately. Most likely You don't have that complex software at Your hand. Please try to specify a case, where You have problem, and ask that as a question – ntohl Feb 21 '17 at 08:52
-
Please explain yourself better, this barley seems like a question. – Koby Douek Feb 21 '17 at 08:52
-
There are 3 types of DI; class constructor, method parameter and property. Pick on for your _code_, preferring the methods in the order given, and then use the class in the test. The choice is made when writing code, not tests. – David Culp Feb 21 '17 at 08:52
-
@RobinHames I believe you mean DI frameworks are used in _code_, but not in _tests_. If the dependencies are injected in the code, they will have to be injected in the tests -- but a DI framework should not be used in the tests. – David Culp Feb 21 '17 at 08:55
-
Possible duplicate of [Why does one use dependency injection?](http://stackoverflow.com/questions/14301389/why-does-one-use-dependency-injection) – Krzysztof Kaczor Feb 21 '17 at 08:59
1 Answers
0
Dependency injection for testing is not really a requirement, but it will really help in unit testing with providing some facilities like the injection of mocks but you could do it manually, it help use of interfaces, no new(), and no singletons etc ...

AKN
- 416
- 2
- 5
-
But why is it best when compared to other like service locator etc. – Priyanka Subramani Feb 21 '17 at 10:12
-
Main objectives of UNIT testing is Test functional units in isolation, this can be done if you can pass dependencies from outside (DI). With the ServiceLocator, the class is still responsible for creating its dependencies. It uses the service locator to do it. With DI, the class is given it's dependencies. It neither knows, nor cares where they come from. One important result of this is that the DI example is much easier to unit test -- because you can pass it mock implementations of its dependent objects. You could combine the two and inject the service locator (or a factory), if you wanted. – AKN Feb 21 '17 at 23:43