Course outline · 0% complete

0/29 lessons0%

Course overview →

Stubs by Hand: Dependency Injection

lesson 5-2 · ~11 min · 14/29

Pass the dependency in

How do you swap a real dependency for a double? The simplest technique is dependency injection, a fancy name for something you already know from Advanced Python: functions are values, so pass the dependency in as a parameter.

def temperature_label(fetch_temp, city):
    t = fetch_temp(city)
    ...

In production, callers hand in the real network function. In tests, you hand in a stub that returns a canned number instantly. The unit cannot tell the difference, and your test becomes fast and deterministic.

This is why testable code and well-designed code are usually the same code: a function that receives its dependencies is also easier to reuse and reason about.

Code exercise · python

Run this. stub_fetch answers from a hard-coded dictionary, so the three tests run instantly with zero network and always get the same temperatures.

Quiz

Why not simply test temperature_label against the real weather API?

Code exercise · python

Your turn. greeting reads the hour from an injected now_hour function. Write stubs (lambda: 9 is enough) to test all five cases, including the boundary probes at exactly 12 and 18 that lesson 3-2 taught you to include. Then print: 5 tests passed without waiting for the clock

Code exercise · python

One more injection rep, solo. shipping_label asks an injected get_country function where an order ships. Stub it twice with lambdas — one returning "US", one returning "PE" — to test both branches, then print: 2 tests passed without a database