How does dependency injection make unit testing easier?
Because the class receives its collaborators, a test can pass in a fake instead of a real database, network or clock. The test runs fast and gives the same result every time.
Explain it simply
To test a driver's skill you use a practice track, not Mumbai traffic. A fake dependency is a practice track: controlled and repeatable. If the class creates its own real database connection inside, the test has no way to swap it out.
Example
class OtpService:
def __init__(self, sms, generator):
self.sms = sms
self.generator = generator
def send(self, phone):
code = self.generator()
self.sms.send(phone, f"Your OTP is {code}")
return code
class FakeSms:
def __init__(self): self.sent = []
def send(self, phone, text): self.sent.append((phone, text))
def test_send():
fake = FakeSms()
svc = OtpService(fake, generator=lambda: 4821) # fixed code
svc.send("9800000000")
assert fake.sent == [("9800000000", "Your OTP is 4821")]
test_send()
print("ok") # okWith a real SMS gateway and a random generator inside the class, this test would cost money and be unpredictable.
What to say in the interview
"With DI, tests inject fakes or mocks for external things such as the database, network, randomness and time. That gives fast, isolated, deterministic tests without changing the production code."
Common mistakes
- Mocking everything, including simple classes, until the test only checks the mock.