Why DI — what changes for testing?
The point
Without DI an object creates its own dependencies: URLSession.shared, Date(), UserDefaults.standard, an analytics singleton. They cannot be replaced in a test, so the test:
- hits the real network/DB — slow and non-deterministic (flaky);
- cannot check edge cases (a network error, a specific date);
- leaves side effects (wrote to
UserDefaults, sent an event).
With DI the dependencies are passed through init, and the test injects test doubles — a stub (returns canned data), a spy (records calls), a fake (a simplified working implementation such as an in-memory repository). The test becomes isolated, fast and repeatable.
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep