DevPrep

All topics › Software architecture

Why DI — what changes for testing?

Middle PRO

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:

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

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store