How does DI facilitate Unit Testing?

Updated Apr 28, 2026

Short answer

DI allows developers to substitute real dependencies with mock or stub implementations during testing.

Deep explanation

If a class directly instantiates a database connection, you cannot test that class without a real database. With DI, you inject an interface, allowing you to pass a fake 'MockDatabase' that returns predefined data, ensuring your test is fast, deterministic, and isolated.

Real-world example

Testing an email notification system without actually sending real emails by injecting a MockEmailSender.

Common mistakes

  • Using real external services in unit tests because the code wasn't designed with DI, resulting in slow, flaky integration tests.

Follow-up questions

  • What is a Mock object?

More Dependency Injection interview questions

View all →