Interview Q&A / Object-Oriented Programming

BeginnerQuick answer1 min readUpdated 3 Oct 2026

How does dependency injection make unit testing easier?

SHORT ANSWER

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

python
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")      # ok

With 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.

#dependency-injection#testing#python

Related questions

Practise more Object-Oriented Programming questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Object-Oriented Programming quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.