8

I used dependency injection in some projects but I didn't fully understand why. I think it is partly to facilitate TDD - if we use dependency injection then many dependencies of the software can be injected/"mocked" and like that we can test them without having the dependency, for instance, an underlying data set that is mocked during the tests instead of supplied as it actually is.

Is this correct or did I misunderstand?

2 Answers 2

6

Yes, proper dependency injection benefits testing and TDD greatly because it allows to test individual components/dependencies easier - mocking/stubing each of the dependencies without affecting any global variables or global dependencies which other parts of an application may depend upon or other tests might use.

I found it quite handy to write unit and integration tests for the AngularJS application - it was very convenient to simulate all sorts of test pre-conditions by just preparing your services or other components and then injecting them into a component under test.

6

The TirePressureMonitoringSystem coding kata is an situation that is very hard to test without dependency injection. It simulates an Alarm which is part of tire pressuring system. The implemented sensor gives back random data. The task is to restructure the Alarm class, but not the sensor to make it unit-testable. I think the kata showcases why DI is so important when doing unit-testing.

Take care you do not fall in the mocking trap, where you mock everything. You don't want to have a lot of change detector tests. You want to test behaviour, not implementation. Making it easier to refactor your code later, not harder.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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